為啥要用addEventListener?
分析一下html代碼
window.onload = function(){
var box = document.getElementById("box");
box.onclick = function(){
console.log("我是box1");
}
box.onclick = function(){
box.style.fontSize = "18px";
console.log("我是box2");
}
}
運(yùn)行結(jié)果:“我是box2”
原因就是很簡(jiǎn)單春畔,第二個(gè)onclick事件把第一個(gè)onclick事件給覆蓋了脱货。雖然大部分時(shí)候岛都,我們用on可以解決,但是如果要有增加多個(gè)相同的事情振峻,on肯定就實(shí)現(xiàn)不了臼疫。對(duì)此就引入今天的主角---addEventListener,多次綁定同一個(gè)時(shí)間扣孟,切不會(huì)覆蓋烫堤。
修改一下上面代碼
window.onload = function(){
var box = document.getElementById("box");
box.addEventListener("click",function(){
console.log("我是box1");
})
box.addEventListener("click",function(){
console.log("我是box2");
})
}
運(yùn)行結(jié)果:我是box1
我是box2
addEventListener總共有三個(gè)參數(shù),第一個(gè)參數(shù)填寫的是事件名稱凤价,記得不需要加on鸽斟,第二個(gè)參數(shù)是函數(shù)方法,第三個(gè)參數(shù)是捕獲或者冒泡的時(shí)候處理利诺,第三個(gè)參數(shù)在大部分情況下都不需要填寫富蓄,默認(rèn)為false。(true--捕獲慢逾,false--冒泡)
第三個(gè)參數(shù)
分別給body和box添加點(diǎn)擊事件
box.addEventListener("click",function(){
console.log("box");
}) //冒泡
child.addEventListener("click",function(){
console.log("child");
})
執(zhí)行的結(jié)果:
child
box
默認(rèn)情況事件是按照事件冒泡的執(zhí)行順序進(jìn)行的立倍。
若參數(shù)為true
box.addEventListener("click",function(){
console.log("box");
},true) //捕獲
child.addEventListener("click",function(){
console.log("child");
})
執(zhí)行的結(jié)果:
box
child
移除事件
一般的onclick事件通過(guò)
box.onclick =null;
賦予為空值,就能正常移除事件了侣滩。
addEcentListener需要使用的是removeEventListener
box.addEventListener("click",function(){
console.log("box");
})
box.removeEventListener("click",function(){
console.log("box");
})
注意:removeEventListener參數(shù)與addEcentListener必須是一致口注。
addEcentListener不支持IE6,IE7君珠,IE8
所以到了IE寝志,我們就用attachEvent方法
<a id="xc">點(diǎn)擊</a>
<script type="text/javascript">
function handler(e){
e=e||window.event;
var _this=e.srcElement||e.target;
alert(_this.innerHTML);
}
var object=document.getElementById('xc');
object.attachEvent('onclick',handler);
</script>