js冲突怎么解决?

JavaScript08

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>

addEvent.exec=function (){

for(var i in this.events[type]){

this.events[type][i]()

}

这段的this结合上面一行事件的绑定代码obj['on' + type] = addEvent.exec,this就是obj对象这点你理解的没错。但

obj['on' + type] = addEvent.exec

obj['on' + type] = function (){

for(var i in this.events[type]){

     this.events[type][i]()

 }

}

是不同的,使用obj['on' + type] = addEvent.exec,addEvent.exec所指的函数中的变量type是获得不到值的,因为addEvent.exec在函数addEvent之外定义,而type变量的作用域仅在addEvent函数内。

所以做以下改动:

将obj['on' + type] = addEvent.exec改为obj['on' + type] = function(){addEvent.exec.apply(this,[type])}

addEvent.exec=function (){

for(var i in this.events[type]){

this.events[type][i]()

}

       加入参数type:

       addEvent.exec=function (type){

for(var i in this.events[type]){

this.events[type][i]()

}

完整代码:

<html>

 <head>

    <meta http-equiv="content-type" content="text/htmlcharset=utf-8">

    <title>百度一下,你就知道</title>

 </head>

 <body>

 <button id="btn">按钮1</button>

 <button  onclick="addEvent(document.getElementById('btn'), 'click',function(){alert('事件处理1.')})">为按钮1绑定click事件1</button>

 <button  onclick="addEvent(document.getElementById('btn'), 'click',function(){alert('事件处理2.')})">为按钮1绑定click事件2</button>

<script>

window.i=1

function addEvent(obj, type, fn) {

//if (typeof obj.addEventListener != 'undefined') {

//obj.addEventListener(type, fn, false)

//} else {

//创建一个存放事件的哈希表(散列表)

if (!obj.events) obj.events = {}

//第一次执行时执行

if (!obj.events[type]) {

//创建一个存放事件处理函数的数组

obj.events[type] = []

//把第一次的事件处理函数先储存到第一个位置上

if (obj['on' + type]) obj.events[type][0] = fn

}

//从第二次开始我们用事件计数器来存储

obj.events[type][addEvent.ID++] = fn

//执行事件处理函数

obj['on' + type] = function(){addEvent.exec.apply(this,[type])}

//}

}

//为每个事件分配一个计数器

addEvent.ID = 1

addEvent.exec=function (type){

for(var i in this.events[type]){

  this.events[type][i]()

}

}

</script>

 </body>

</html>