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);
答案 0 :(得分:2)
document.body.removeEventListener("click", delElm);
删除整个页面的所有“ onclick”事件
不,不是。但这确实是
document.body.innerHTML += "<div id='dynamicLinkCheckOutput'></div>";
在+=
上使用innerHTML
会强制浏览器:
body
中的所有元素,为它们构建HTML字符串。innerHTML
的字符串,清除body
中的所有元素(从而失去事件处理程序和大多数其他状态),并创建 new ,从解析的HTML中替换它们的元素。如果要附加到body
(或其他任何元素),请不要使用innerHTML += x
,请使用:
document.body.insertAdjacentHTML("beforeend", "<div id='dynamicLinkCheckOutput'></div>");
或
var div = document.createElement("div");
div.id = "dynamicLinkCheckOutput";
document.body.appendChild(div);
或
其他各种DOM方法。更多探索:DOM on MDN。