[英]document.body.removeEventListener removes ALL click event listeners (not the specified function) why?
document.body.removeEventListener("click", delElm);
removes all "onclick" events for the entire page. 删除整个页面的所有“ onclick”事件。 why?
为什么? Am I not clearly specifying what function I want removed from the document.body?
我是否没有明确指定要从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);
document.body.removeEventListener("click", delElm);
removes all "onclick" events for the entire page
删除整个页面的所有“ onclick”事件
No, it doesn't. 不,不是。 But this does:
但这确实是:
document.body.innerHTML += "<div id='dynamicLinkCheckOutput'></div>";
Using +=
on innerHTML
forces the browser to: 在
innerHTML
上使用+=
强制浏览器执行以下操作:
body
building an HTML string for them. body
所有元素,为它们构建HTML字符串。 innerHTML
by the JavaScript layer, wipe out all elements within body
(thus losing their event handlers and most other state), and create new , replacement elements for them from the parsed HTML. innerHTML
的字符串,擦除body
所有元素(从而失去其事件处理程序和大多数其他状态),并从解析的HTML中为其创建新的替换元素。 If you want to append to body
(or any other element), don't use innerHTML += x
, use: 如果要附加到
body
(或任何其他元素),请不要使用innerHTML += x
,请使用:
insertAdjacentHTML
: insertAdjacentHTML
:
document.body.insertAdjacentHTML("beforeend", "<div id='dynamicLinkCheckOutput'></div>");
or 要么
createElement
and appendChild
: createElement
和appendChild
:
var div = document.createElement("div"); div.id = "dynamicLinkCheckOutput"; document.body.appendChild(div);
or 要么
Various other DOM methods. 其他各种DOM方法。 More to explore: DOM on MDN .
更多探索: MDN上的DOM 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.