[英]document.body.removeEventListener not working for removing listener for keypress event
[英]document.body.removeEventListener removes ALL click event listeners (not the specified function) why?
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);
document.body.removeEventListener("click", delElm);
刪除整個頁面的所有“ onclick”事件
不,不是。 但這確實是:
document.body.innerHTML += "<div id='dynamicLinkCheckOutput'></div>";
在innerHTML
上使用+=
強制瀏覽器執行以下操作:
body
所有元素,為它們構建HTML字符串。 innerHTML
的字符串,擦除body
所有元素(從而失去其事件處理程序和大多數其他狀態),並從解析的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方法。 更多探索: MDN上的DOM 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.