-
29-09-2019 - |
题
无论如何,是否在那里删除了这样的事件侦听器:
element.addEventListener(event, function(){/* do work here */}, false);
不替换元素?
解决方案
除非您在Creation中存储了对事件处理程序的引用,否则无法干净地删除事件处理程序。
我通常会将它们添加到该页面上的主要对象中,然后您可以在使用该对象时迭代并清洁它们。
其他提示
您可以这样删除活动听众:
element.addEventListener("click", function clicked() {
element.removeEventListener("click", clicked, false);
}, false);
匿名的 边界 活动听众
删除所有事件听众的最简单方法是分配其 outerHTML
对自己。这样做的是通过HTML解析器发送HTML的字符串表示,并将解析的HTML分配给元素。因为没有通过JavaScript传递,所以将无绑定的事件听众。
document.getElementById('demo').addEventListener('click', function(){
alert('Clickrd');
this.outerHTML = this.outerHTML;
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
匿名的 委派 活动听众
一个警告是委派的活动听众,或者是父母元素上的事件听众,该事件观察每个事件都符合其孩子的一组标准。超越的唯一方法是改变元素以不符合委派事件听众的标准。
document.body.addEventListener('click', function(e){
if(e.target.id === 'demo') {
alert('Clickrd');
e.target.id = 'omed';
}
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
您可以尝试覆盖 element.addEventListener
并做任何您想做的事。
就像是:
var orig = element.addEventListener;
element.addEventListener = function (type, listener) {
if (/dontwant/.test(listener.toSource())) { // listener has something i dont want
// do nothing
} else {
orig.apply(this, Array.prototype.slice.apply(arguments));
}
};
ps。:不建议这样做,但它会解决问题(尚未测试)
编辑: 作为 Manngo 建议按评论,您应该使用 。离开() 代替 .unbind() 作为 .unbind() 从jQuery 3.0开始弃用,自JQuery 1.7以来被取代。
即使这是一个古老的问题,也没有提及jQuery,我也会在这里发布答案,因为这是搜索术语的第一个结果 'jQuery删除匿名活动处理程序'.
您可以尝试使用 。离开() 功能。
$('#button1').click(function() {
alert('This is a test');
});
$('#btnRemoveListener').click(function() {
$('#button1').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Click me</button>
<hr/>
<button id="btnRemoveListener">Remove listener</button>
但是,这仅在您使用jQuery添加侦听器时才有效 - 不 .addeventListener
找到了这个 这里.
用字面函数分配事件处理程序很棘手 - 不仅没有任何方法可以删除它们,而不会克隆节点并用克隆替换它 - 您还可以无意中多次分配同一处理程序,如果您使用使用引用处理程序。即使角色相同,两个函数也总是将其视为两个不同的对象。
旧问题,但这是一个解决方案。
严格来说,除非您存储对该功能的引用,否则您不能删除匿名事件侦听器。由于使用匿名函数的目标可能不是创建新变量,因此您可以将参考存储在元素本身中:
element.addEventListener('click',element.fn=function fn() {
// Event Code
}, false);
稍后,当您要删除它时,您可以执行以下操作:
element.removeEventListener('click',element.fn, false);
请记住,第三个参数(false
)必须有 相同的 值与添加事件侦听器一样。
但是,问题本身乞求另一个:为什么?
使用两个原因 .addEventListener()
而不是简单 .onsomething()
方法:
首先,它允许 多 要添加的活动听众。当涉及到选择性地删除它们时,这成为一个问题:您可能最终会命名它们。如果您想全部删除它们,那么 @Tidy-Giant outerHTML
解决方案非常好。
其次,您确实可以选择选择捕获而不是冒泡事件。
如果这两个原因都不重要,您可能会决定使用更简单的 onsomething
方法。
以下对我来说足够好。该代码处理另一个事件触发侦听器从元素中删除的情况。不需要事先发出功能声明。
myElem.addEventListener("click", myFunc = function() { /*do stuff*/ });
/*things happen*/
myElem.removeEventListener("click", myFunc);
如果您正在使用jQuery尝试 off
方法
$("element").off("event");
jQuery .off()方法删除了与.on附加的事件处理程序()
使用Ecmascript2015(ES2015,ES6)语言规范,可以使用此操作 nameAndSelfBind
神奇地将匿名回调变成指定的功能,甚至将其身体绑定到自身,使事件侦听器从内部删除自身,并从外部范围中删除它(JSFIDDLE):
(function()
{
// an optional constant to store references to all named and bound functions:
const arrayOfFormerlyAnonymousFunctions = [],
removeEventListenerAfterDelay = 3000; // an auxiliary variable for setTimeout
// this function both names argument function and makes it self-aware,
// binding it to itself; useful e.g. for event listeners which then will be able
// self-remove from within an anonymous functions they use as callbacks:
function nameAndSelfBind(functionToNameAndSelfBind,
name = 'namedAndBoundFunction', // optional
outerScopeReference) // optional
{
const functionAsObject = {
[name]()
{
return binder(...arguments);
}
},
namedAndBoundFunction = functionAsObject[name];
// if no arbitrary-naming functionality is required, then the constants above are
// not needed, and the following function should be just "var namedAndBoundFunction = ":
var binder = function()
{
return functionToNameAndSelfBind.bind(namedAndBoundFunction, ...arguments)();
}
// this optional functionality allows to assign the function to a outer scope variable
// if can not be done otherwise; useful for example for the ability to remove event
// listeners from the outer scope:
if (typeof outerScopeReference !== 'undefined')
{
if (outerScopeReference instanceof Array)
{
outerScopeReference.push(namedAndBoundFunction);
}
else
{
outerScopeReference = namedAndBoundFunction;
}
}
return namedAndBoundFunction;
}
// removeEventListener callback can not remove the listener if the callback is an anonymous
// function, but thanks to the nameAndSelfBind function it is now possible; this listener
// removes itself right after the first time being triggered:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
e.target.removeEventListener('visibilitychange', this, false);
console.log('\nEvent listener 1 triggered:', e, '\nthis: ', this,
'\n\nremoveEventListener 1 was called; if "this" value was correct, "'
+ e.type + '"" event will not listened to any more');
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to prove that deanonymized functions -- even when they have the same 'namedAndBoundFunction'
// name -- belong to different scopes and hence removing one does not mean removing another,
// a different event listener is added:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
console.log('\nEvent listener 2 triggered:', e, '\nthis: ', this);
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to check that arrayOfFormerlyAnonymousFunctions constant does keep a valid reference to
// formerly anonymous callback function of one of the event listeners, an attempt to remove
// it is made:
setTimeout(function(delay)
{
document.removeEventListener('visibilitychange',
arrayOfFormerlyAnonymousFunctions[arrayOfFormerlyAnonymousFunctions.length - 1],
false);
console.log('\nAfter ' + delay + 'ms, an event listener 2 was removed; if reference in '
+ 'arrayOfFormerlyAnonymousFunctions value was correct, the event will not '
+ 'be listened to any more', arrayOfFormerlyAnonymousFunctions);
}, removeEventListenerAfterDelay, removeEventListenerAfterDelay);
})();