Javascript removeEventListener not working - event listener remains

后端 未结 3 506
一生所求
一生所求 2021-01-20 06:05

I\'ve looked at a few ways around this, but I can\'t really tell, my code is:

lb = document.body;

if(lb.addEventListener){    
    lb.addEventListener(\'key         


        
3条回答
  •  [愿得一人]
    2021-01-20 06:44

    When calling removeEventListener, you have to give it the same function instance than to addEventListener:

    var lb = document.body;
    
    var callback = function(event){
        keyPress(event.keyCode)
    };
    
    if(lb.addEventListener){    
        lb.addEventListener('keyup', callback, false);
    }
    
    //In another function.
    
    if(document.body.removeEventListener){
        document.body.removeEventListener('keyup', callback, false);
    }
    

    jQuery makes it easier to deal with this, thanks to its namespaced events feature:

    $(lb).on('keyup.my_namespace', function () { ... })
    
    // later
    
    $(lb).off('keyup.my_namespace');
    

提交回复
热议问题