无法删除事件侦听器 [英] Can't remove event listener

查看:134
本文介绍了无法删除事件侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉为什么 bt2 如果阻止,中的事件侦听器不会被删除。当我在 p 函数中删除事件监听器时,它被删除而没有任何错误或错误。我很确定可能存在任何堆栈或范围问题,因为哪个事件监听器没有被删除但我无法弄清楚它可能是什么。我知道事件监听器没有被删除,因为随后点击 bt2 元素,所有前面的事件监听器也会再次运行,因为同一个函数正在运行多次。请告诉我这是什么问题。



以下是完整代码:

 (function()
{
if(window.addEventListener)window.addEventListener('load',init,false);
函数init()
{var i = 0;
var get = document.getElementById('bt1')。addEventListener('click',function(){pro(0);},false);

function pro(x)
{alert( '是啊');
if(!x)x = 0
if(x!= 0)//我不想在第一次删除事件监听器,所以我希望它能够与下一次调用pro,其中x的值大于0
{
// alert('right');
document.getElementById('bt2')。removeEventListener('click ',p,false); //事件监听器没有被删除。
}
document.getElementById('bt2')。innerHTML ='这是一个按钮'+ x;
function passTo(y)
{
pro(y);
}
document.getElementById('bt2')。addEventListener('click',p,false);
function p()
{//document.getElementById('bt2').removeEventListener('click',p,false); //这里事件监听器很容易被删除
passTo(x + 1);
}

}
}
}());


解决方案

removeEventListener 要求您传递相同的功能,但您的 p 功能不同:每次<$创建一个新的<$>调用c $ c> pro 。因此,您要删除的内容不是您添加的内容,因此不会删除。



在中删除 p 有效,因为在每个 p 函数中,标识符 p 特定的 p 函数。因此,如果添加了那个,它将成功删除。



您可以通过在函数上添加唯一标识符来证明这一点(请参阅注释):



< pre class =snippet-code-js lang-js prettyprint-override> (function(){if(window.addEventListener)window.addEventListener('load',init,false); var functionId = 0; //为我们提供唯一ID函数的函数init(){var i = 0; var get = document.getElementById('bt1')。addEventListener('click',function(){pro(0);},false ); function pro(x){snippet.log('yeah'); //我们总是进入这个if的主体,条件//只是在这里强调if(!p.id){p.id = ++ functionId;} if(!x)x = 0 if(x!= 0){ snippet.log(正在删除#+ p.id); //< === document.getElementById('bt2')。removeEventListener('click',p,false); } document.getElementById('bt2')。innerHTML ='这是一个按钮'+ x; function passTo(y){pro(y); } snippet.log(添加#+ p.id); //< === document.getElementById('bt2')。addEventListener('click',p,false); function p(){passTo(x + 1); }}}}());

 < button id =bt1> bt1< / button>< button id =bt2> bt2< / button><! - 脚本提供`snippet`对象,请参阅http://meta.stackexchange.com/ a / 242144/134069  - >< script src =// tjcrowder.github.io/simple-snippets-console/snippet.js\"></script>



如果我们运行并点击 bt1 一次,那么反复点击 bt2 ,我们看到:

 
是啊
添加#1
是啊
删除#2
添加#2
是啊
删除#3
添加#3
是啊
删除#4
添加#4

注意我们每次尝试删除不同的函数时的效果我们添加了。



如果你想删除前一个,你需要在别处记住它(见评论)



 (function(){if(window.addEventListener)window。 addEventListener('load',init,false); var functionID = 0; var lastp = null; //< === function init(){var i = 0; var get = document.getElementById('bt1')。addEventListener('click',function(){pro(0);},false); function pro(x){snippet.log('yeah'); if(!p.id){//再次,总是真的p.id = ++ functionID; } if(!x)x = 0; if(lastp)//< === {snippet.log(删除#+ lastp.id); document.getElementById('bt2')。removeEventListener('click',lastp,false); } document.getElementById('bt2')。innerHTML ='这是一个按钮'+ x; function passTo(y){pro(y); } lastp = p; //< === snippet.log(添加#+ p.id); document.getElementById('bt2')。addEventListener('click',p,false); function p(){passTo(x + 1); }}}}());  

 < button id =bt1> bt1< / button>< button id =bt2> bt2< / button><! - 脚本提供`snippet`对象,请参阅http://meta.stackexchange.com/ a / 242144/134069  - >< script src =// tjcrowder.github.io/simple-snippets-console/snippet.js\"></script>


Can anyone tell why bt2 event listener is not getting removed in if block. As when I remove the event listener in the p function, it's getting removed without any error or bug. I am pretty sure there might be any stack or scope problem due to which event listener is not getting removed but I can't figure out what that could be. And I know that event listener is not getting removed as with the succeeding clicks on bt2 element all the preceding event listeners are also running again, as the same function is running multiple times. Please tell me what's the problem.

Here's the full code:

    (function()
    {
        if(window.addEventListener) window.addEventListener('load',init,false);
        function init()
        {   var i=0;
            var get=document.getElementById('bt1').addEventListener('click',function() { pro(0);},false);

            function pro(x)
            {   alert('yeah');
                if(!x) x=0
                if(x!=0) //I dont want to remove event listener in the first time , so i want it to function with the next call to pro,in which the value of x is bigger than 0                
{
                    //alert('right'); 
                      document.getElementById('bt2').removeEventListener('click',p,false); //event listener is not getting removed .
                }
                document.getElementById('bt2').innerHTML='this is a button '+x;
                function passTo(y)
                {   
                    pro(y);     
                }
                document.getElementById('bt2').addEventListener('click',p,false);
                function p()
                {   //document.getElementById('bt2').removeEventListener('click',p,false); //here the event listener is getting removed easily
                    passTo(x+1);
                }

            }
        }
    }());

解决方案

removeEventListener requires that you pass it the same function, but your p functions are not the same: A new one is created every time pro is called. So the one you're trying to remove isn't the one you added, and so it isn't removed.

Removing it within p works, because within each p function, the identifier p refers to that specific p function. So if that one's been added, it will successfully remove itself.

You can prove this to yourself by putting a unique identifier on your function (see comments):

(function() {
    if (window.addEventListener) window.addEventListener('load', init, false);

    var functionId = 0; // Something to give us unique IDs

    function init() {
        var i = 0;
        var get = document.getElementById('bt1').addEventListener('click', function() {
            pro(0);
        }, false);

        function pro(x) {
            snippet.log('yeah');
            // We ALWAYS to into the body of this if, the condition
            // is just here for emphasis
            if (!p.id) {
                p.id = ++functionId;
            }
            if (!x) x = 0
            if (x != 0)
            {
                snippet.log("Removing #" + p.id); // <===
                document.getElementById('bt2').removeEventListener('click', p, false);
            }
            document.getElementById('bt2').innerHTML = 'this is a button ' + x;

            function passTo(y) {
                pro(y);
            }
            snippet.log("Adding #" + p.id); // <===
            document.getElementById('bt2').addEventListener('click', p, false);

            function p() { 
                passTo(x + 1);
            }

        }
    }
}());

<button id="bt1">bt1</button>
<button id="bt2">bt2</button>

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

If we run that and click bt1 once, then repeatedly click bt2, we see:

yeah
Adding #1
yeah
Removing #2
Adding #2
yeah
Removing #3
Adding #3
yeah
Removing #4
Adding #4

Note how each time we're trying to remove a different function than we added.

If you want to remove the previous one, you need to remember it elsewhere (see comments):

(function() {
    if (window.addEventListener) window.addEventListener('load', init, false);

    var functionID = 0;
    var lastp = null; // <===

    function init() {
        var i = 0;
        var get = document.getElementById('bt1').addEventListener('click', function() {
            pro(0);
        }, false);

        function pro(x) {
            snippet.log('yeah');
            if (!p.id) { // Again, always true
                p.id = ++functionID;
            }
            if (!x) x = 0;
            if (lastp) // <===
            {
                snippet.log("Removing #" + lastp.id);
                document.getElementById('bt2').removeEventListener('click', lastp, false);
            }
            document.getElementById('bt2').innerHTML = 'this is a button ' + x;

            function passTo(y) {
                pro(y);
            }
            lastp = p; // <===
            snippet.log("Adding #" + p.id);
            document.getElementById('bt2').addEventListener('click', p, false);

            function p() { 
                passTo(x + 1);
            }

        }
    }
}());

<button id="bt1">bt1</button>
<button id="bt2">bt2</button>

<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

这篇关于无法删除事件侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆