js冲突怎么解决?

JavaScript09

js冲突怎么解决?,第1张

jQuery多个版本或和其他js库冲突主要是常用的$符号的问题,主要解决办法如下:

方法一:

<script type="text/javascript">jQuery.noConflict() //将变量$的控制权让渡给prototype.jsjQuery(function(){ //使用jQueryjQuery("p").click(function(){

alert( jQuery(this).text() )

})

})

$("pp").style.display = 'none' //使用prototype</script>

方法二:

<script type="text/javascript">var $j = jQuery.noConflict() //自定义一个比较短快捷方式$j(function(){ //使用jQuery$j("p").click(function(){

alert( $j(this).text() )

})

})

$("pp").style.display = 'none' //使用prototype</script>

方法三:

<script type="text/javascript">jQuery.noConflict() //将变量$的控制权让渡给prototype.js(function($){ //定义匿名函数并设置形参为$$(function(){ //匿名函数内部的$均为jQuery$("p").click(function(){ //继续使用 $ 方法alert($(this).text())

})

})

})(jQuery) //执行匿名函数且传递实参jQuery$("pp").style.display = 'none' //使用prototype</script>

冲突的原因:第一个中$被定义为jquery的对象了,而你第二个中有再次定义这样的全局变量,变量冲突了,解决的方法有两个:

第一种,把你的第二个改成(推荐方法):

<script

type="text/javascript">

$(function

()

{

$("#nav").next().click(function(){

$(this).toggle()

})

})

</script>

第二种,把你的第二个改成(不推荐):

<script

type="text/javascript">

function

$$(id){return

document.getElementById(id)}//注意改成$$

window.onload

=

function(){

$$("nav").onclick

=

function(e){

var

src

=

e?e.target:event.srcElement

if(src.tagName

==

"H3"){

var

next

=

src.nextElementSibling

||

src.nextSibling

next.style.display

=

(next.style.display

=="block")?"none":"block"

}

}

}

</script>

有什么不明白的可以继续追问我。