事件解绑

页面刷新后,点击div,能执行函数,说明这个事件被存到了内存中
因为事件点击一次过后,还能点击,内存中存的事件一直没有删除,一直停留在内存中
对于内存来说,就是一种资源浪费
解绑:将事件取消掉,对资源的一种节省
var box = document.getElementsByTagName('div')[0];
 box.onclick = function(){
     console.log("点击了div");

     box.onclick = null // 事件解绑
 }

addEventListener对应着有一个解绑的方法 - removeEventlistener - 匿名函数解绑不了

box.addEventListener('click',function(){
     console.log("点击了div");
     box.removeEventListener('click',function(){
         console.log("点击了div");
         box.removeEventListener('click',fn)
     })
 })

 

封装解绑函数

function removeEvent(ele,type,handler){
    if(ele.removeEventListener){
        ele.removeEventListener(type,handler)
    }else if(ele.detachEvent){
        ele.detachEvent('on'+type,handler)
    }else{
        ele['on' + type] = null
    }
}

 

 

posted @ 2021-01-11 21:17  技术活当赏  阅读(126)  评论(0)    收藏  举报