简体   繁体   English

添加和删​​除事件监听器-JavaScript

[英]Add and Remove Event Listener - JavaScript

I am trying to add addEventListener when I click on a div. 我在单击div时试图添加addEventListener。 I already found many questions and answers but I didn't achieve to make it works. 我已经找到了很多问题和答案,但是并没有使它起作用。 Actually, I would like to pass some parameters to my eventListener. 实际上,我想将一些参数传递给我的eventListener。

At the beginning I tried this: 一开始我尝试了这个:

document.getElementsByClassName('my-div')[0].addEventListener('click', customFunction(event, args1, args2));

But it was not working. 但这没有用。 Indeed, on a click it was not going into customFunction . 确实,单击一下就不会进入customFunction

Therefore, I tried with bind : 因此,我尝试使用bind

document.getElementsByClassName('my-div')[0].addEventListener('click', customFunction.bind(null, event, args1, args2));

This time, on a click it was passing into customFunction . 这次,单击将其传递给customFunction

However, the param event is type Event and not MouseEvent. 但是,参数事件是Event类型,而不是MouseEvent类型。 In the event object I don't have access to the currentTarget or things that I found usually in an event with addEventListener. 在事件对象中,我无权访问currentTarget或通常在具有addEventListener的事件中找到的东西。

屏幕截图事件

This is may due because here event is Event type whereas usually it is MouseEvent type. 这可能是由于这里的事件是事件类型,而通常是MouseEvent类型。

I though to use anonymous function like this: 我虽然使用这样的匿名函数:

element.addEventListener("click", function() {
  // do something
});

But I need to remove the eventListener and with anynomous function it is not cleaned to do so. 但是我需要删除eventListener,并使用任意函数将其清除。 It's better to store the object function in order to remove the addEventListener after that. 最好存储对象函数以便在此之后删除addEventListener。

What should I do ? 我该怎么办 ?

Try by putting the customFunction inside the callback function like this 尝试将customFunction放在这样的回调函数中

 document.getElementsByClassName('my-div')[0].addEventListener('click', function(event) { customFunction(event, args1, args2) }); 

For removing event use removeEventListener 要删除事件,请使用removeEventListener

You can JQuery to bind event 您可以通过JQuery绑定事件

 $( "#target" ).click(function() { alert( "Handler for .click() called." ); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="target"> Click here </div> <div id="other"> Trigger the handler </div> 

REF : JQuery Click Event REF: jQuery单击事件

Replace alert with your function 用您的功能替换警报

    const clickEventListener = ['click', function (event) { 
      customFunction(event, args1, args2) 
    }];
    element.addEventListener(...clickEventListener);
    element.removeEventListener(...clickEventListener);

This fix my problem. 这解决了我的问题。

medium link 媒体链接

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

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