只是提问:有没有办法彻底删除对象的所有事件,例如div?
编辑:我正在添加div.addEventListener('click',eventReturner(),false);一个事件.
function eventReturner() {
return function() {
dosomething();
};
}
Run Code Online (Sandbox Code Playgroud)
EDIT2:我找到了一种方法,但是不能用于我的情况:
var returnedFunction;
function addit() {
var div = document.getElementById('div');
returnedFunction = eventReturner();
div.addEventListener('click',returnedFunction,false); //You HAVE to take here a var and not the direct call to eventReturner(), because the function address must be the same, and it would change, if the function was called again.
}
function removeit() {
var div = document.getElementById('div');
div.removeEventListener('click',returnedFunction,false);
}
Run Code Online (Sandbox Code Playgroud) 是否可以删除元素及其子元素的所有事件侦听器?就像是:
myElem.removeEventListeners();
Run Code Online (Sandbox Code Playgroud)
我需要这个,因为我有一个复杂的事件元素,我需要创建它的副本 - 就像一个静态图像,不会对任何事件做出反应.
请检查以下代码,
var clickfn = function(){
alert("clicked");
}
document.getElementById("div1").addEventListener("click",clickfn,true);
clickfn = function(){ };
document.getElementById("div1").removeEventListener("click");
Run Code Online (Sandbox Code Playgroud)
为什么removeEventListener不起作用?
谢谢!
这个问题基本上就是我要问的问题,但是没有为后代节点删除事件的限制.
在这个小提琴中,我尝试通过从DOM中删除它并将其放回来删除附加的侦听器.
function removeListeners(el) {
var par = el.parentNode;
var place = el.nextSibling;
par.removeChild(el);
par.insertBefore(el, place);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,这不起作用,你仍然可以点击以获得改变的背景(这实际上很好,我从来不知道你可以附加没有元素在DOM中的事件).
鉴于这一发现我试过这个
function removeListeners(el) {
var par = el.parentNode;
var clone = el.cloneNode(false);
par.replaceChild(clone, el);
for (var index = 0; index < el.childNodes.length; ++index)
clone.appendChild(el.childNodes[index]);
}
Run Code Online (Sandbox Code Playgroud)
尝试做一个浅层克隆,然后将所有后代复制回来,但它不会复制所有孩子.
在上述问题的回答说:"[如果你想有孩子们保持他们的听众]你将不得不求助于明确地去除听众一次一个".我不知道你将如何实现这一点.
我认为他的意思是获取事件类型列表并依次删除每个事件的侦听器(如jQuery可以).这不仅对自定义事件不可能,而且vanilla JS 没有这样的功能(您必须指定要删除的功能).
我正在尝试从某个网站上删除事件侦听器,但没有成功。
有一个 javascript 脚本可以创建这些事件:
document.addEventListener('contextmenu', function (ev) {
ev.preventDefault();
}
)
Run Code Online (Sandbox Code Playgroud)
我试图用以下方法删除它:
document.removeEventListener('contextmenu', function (ev) {
ev.preventDefault();
})
Run Code Online (Sandbox Code Playgroud)
我也试过:
(getEventListeners(document)).contextmenu = null
Run Code Online (Sandbox Code Playgroud)
但它没有用,我想是因为我使用了一个不同的新功能。
有没有办法清除所有事件?
参考:
无法删除事件侦听器