问题
有个组件,需要移除 dom 及下面所有元素的事件监听
function recreateNode(el, withChildren) {
if (withChildren) {
el.parentNode.replaceChild(el.cloneNode(true), el);
} else {
const newEl = el.cloneNode(false);
while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
el.parentNode.replaceChild(newEl, el);
}
}
var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
人才啊,复制了一份 Dom 进行替换,就移除掉了
- https://stackoverflow.com/questions/4386300/javascript-dom-how-to-remove-all-event-listeners-of-a-dom-object
- https://stackoverflow.com/questions/9251837/how-to-remove-all-listeners-in-an-element
- https://stackoverflow.com/questions/19469881/remove-all-event-listeners-of-specific-type
- https://stackoverflow.com/questions/65495153/remove-all-event-listeners-from-an-element-javascript
后记
开始有想过用 EventTarget.removeEventListener
方法,但是这个方法得第二个参数需要传入原来的监听事件,而这时候我拿不到这个事件。