事件绑定的方式
1) ele.onXXX = function(event) {}
this 指向 dom
2) ele.addEventListener(type, fn, false);一个事件可以绑定多个函数
this 指向 dom
3) ele.attachEvent('on'+type, fn);
this 指向 window(更改方法如下:)
复制代码
var div = document.getElementsByTagName('div')[0];
div.attachEvent('onclick', function(){
handle.call(div);
});
function handle(){
//事件处理函数
}
复制代码
封装兼容性的事件绑定方法
function addEvent(elem, type, handle){
if(elem.addEventListener){
elem.addEventListener(type, handle, false);
}else if(elem.attachEvent){
elem.attachEvent('on'+type, function(){
handle.call(elem);
})
}else{
elem['on'+type] = handle;
}
}
复制代码
解除事件绑定
1) ele.onXXX = false/''/null;
2) ele.removeEventListener('click', test, false);
div.addEventListener('click', test, false);
function test(){
console.log('a');
}
div.removeEventListener('click', test, false);
复制代码
3) ele.detachEvent('on' + type, fn);
若绑定匿名函数,则无法解除。