document.body.removeEventListener删除所有单击事件侦听器(不是指定的函数),为什么?

时间:2018-11-13 19:19:32

标签: javascript dom

document.body.removeEventListener("click", delElm);

删除整个页面的所有“ onclick”事件。为什么?我是否没有明确指定要从document.body中删除的功能?

document.body.innerHTML += "<div id='dynamicLinkCheckOutput'></div>";
var dynamicLinkCheckOutput = document.getElementById('dynamicLinkCheckOutput');

function delElm(e){
    var dynamicLinkCheckOutput = document.getElementById('dynamicLinkCheckOutput');        
       dynamicLinkCheckOutput.parentNode.removeChild(dynamicLinkCheckOutput);
    //document.body.removeEventListener("click", delElm); //moved for clairity
}
setTimeout(function(){
    dynamicLinkCheckOutput.onclick = function(e){
        e.stopPropagation();
    };
    document.body.addEventListener("click", delElm);
    document.body.removeEventListener("click", delElm); //ALL click events from ALL elements have been removed the moment this line executes. 
}, 0);

1 个答案:

答案 0 :(得分:2)

document.body.removeEventListener("click", delElm);
     

删除整个页面的所有“ onclick”事件

不,不是。但这确实是

document.body.innerHTML += "<div id='dynamicLinkCheckOutput'></div>";

+=上使用innerHTML会强制浏览器:

  • 遍历body中的所有元素,为它们构建HTML字符串。
  • 将该字符串返回到JavaScript层,然后将其添加到右侧的字符串上。
  • 解析由JavaScript层分配回innerHTML的字符串,清除body中的所有元素(从而失去事件处理程序和大多数其他状态),并创建 new ,从解析的HTML中替换它们的元素。

如果要附加到body(或其他任何元素),请不要使用innerHTML += x,请使用:

  • insertAdjacentHTML

    document.body.insertAdjacentHTML("beforeend", "<div id='dynamicLinkCheckOutput'></div>");
    

  • createElementappendChild

    var div = document.createElement("div");
    div.id = "dynamicLinkCheckOutput";
    document.body.appendChild(div);
    

  • 其他各种DOM方法。更多探索:DOM on MDN