简体   繁体   English

removeEventListener不起作用

[英]removeEventListener not working

Adds listener 添加监听器

for ( i = 0; i < kbButtons.length; i++ ) {
        kbButtons[i].addEventListener("click", function() { clickKbButton( this ); }, false);
    }

Should remove listener 应该删除监听器

function clickKbButton ( elem ) { 
    elem.removeEventListener("click", function() { clickKbButton( this ); }, false);
    elem.id = "invis"
    }

Everything is working fine, no errors in console, button click works but it's not being removed after I click it 一切正常,在控制台中没有错误,单击按钮仍然有效,但是单击后并未将其删除

As per documentation , my guess is that event handler should reference the same function: 根据文档 ,我的猜测是事件处理程序应该引用相同的函数:

for ( i = 0; i < kbButtons.length; i++ ) {
    kbButtons[i].addEventListener("click", clickKbButton, false);
}
function clickKbButton ( ev ) { 
    this.removeEventListener("click", clickKbButton, false);
    this.id = "invis"
}

Simple fiddle example 简单的小提琴例子

I guess you should use a variable reference to the function() { clickKbButton(this); } 我猜您应该使用对function() { clickKbButton(this); }的变量引用function() { clickKbButton(this); } function() { clickKbButton(this); } , the two functions in your addEventListener & removeEventListener are actually two different functions. function() { clickKbButton(this); }addEventListenerremoveEventListener中的两个函数实际上是两个不同的函数。

var handler = function() { clickKbButton(this) };

then use this handler variable when you add & remove listener. 然后在添加和删除侦听器时使用此处理程序变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM