代码之家  ›  专栏  ›  技术社区  ›  user8293395

激活事件侦听器时删除事件侦听器

  •  1
  • user8293395  · 技术社区  · 7 年前

    我可以很好地激活事件监听器,但是在激活事件监听器后让它自己删除它,到目前为止,我还无法做到。到目前为止,通过我自己的研究,我的理解是,附加到事件侦听器的函数需要以某种方式命名,删除事件侦听器需要能够删除该名称。我试过了,但没能让它工作,因为它导致了无法再识别“e”的问题。这是我的代码:

    that.enter = function(imageID, textID) {
        // Listen for the ENTER key and mouse click.
        console.log('Add event listeners...');
        console.log(imageID + ' ' + textID);
        document.addEventListener('keydown', function(e) { 
            if (e.which === 13) {
                document.getElementById(imageID).click();
                console.log('keydown activated');
                console.log('removing keydown... ');
                document.removeEventListener('keydown', function(e){});
                console.log('keydown removed');
            }
        });
        document.addEventListener('click', function(e) { 
            if (e.target.id != imageID && e.target.id != textID) {
                document.getElementById(imageID).click();
                console.log('click activated');
                console.log('removing click... ');
                document.removeEventListener('click', function(e){});
                console.log('click removed');
            }
        });
        console.log('DONE');
    };
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   CertainPerformance    7 年前

    将函数放入变量中,这样以后使用时就可以引用它 removeEventListener 。Eg公司

    document.addEventListener('keydown', theListener);
    function theListener(e) { 
        if (e.which === 13) {
            document.getElementById(imageID).click();
            console.log('keydown activated');
            console.log('removing keydown... ');
            document.removeEventListener('keydown', theListener);
            console.log('keydown removed');
        }
    }
    

    第二个参数 删除EventListener 必须与中使用的函数完全相同 addEventListener -它不会识别您刚刚声明为在侦听器列表中的新函数。