<div></div>
//事件绑定的方法
div.onclick = function (){} //function里的this指向DIV
-----------------------------------------------
//obj.addEventListener(type,fn,false) IE9以下不兼容,可以为一个事件绑定多个处理程序 function里的this指向div
div.addEventListener(‘click‘,function (){},false);
div.addEventListener(‘click‘,test,false);
function test(){
//....
}
---------------------------------------------------
//obj.attachEvent(on+‘type‘,fn) IE独有,一个事件可以绑定多个处理函数 this指向window
div.attachEvent(‘onclick‘,function(){
handle.call(div);
})
function haddle(){
this//......
}
//解决this指向的问题
------------------------------------------------
//事件绑定函数封装
1 function addEvent(elem,type,handle){ 2 if(elem.addEventListener){ 3 elem.addEventListener(type,handle,false); 4 }else if(elem.attachEvent){ 5 elem.attachEvent(‘on‘+type,function (){ 6 handle.call(elem); 7 }) 8 }else{ 9 elem[‘on‘+type] = handle; 10 } 11 12 } 13 14 addEvent(div,click,fn);
//解除事件绑定
elem.onclick = null;
elem.removeEventListener(type,fn,false);
elem.dettachEvent(‘on‘+type,fn);
原文地址:https://www.cnblogs.com/Lemon-Vinegar/p/8823938.html