Javascript 检查元素上是否有事件侦听器。没有 jQuery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28056716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:09:41  来源:igfitidea点击:

Check if an element has event listener on it. No jQuery

javascript

提问by kevinkarl22

How to check if an element has event listener on it, if I use an inline function on it like the code below? Because I have a function that recalls the function and add the event listener, but it cause to have duplication event listener causing it to trigger a function twice. How can I check it so I can prevent it to add an event listener if is it already exist?

如果我在其上使用内联函数(如下面的代码),如何检查元素是否具有事件侦听器?因为我有一个函数可以调用该函数并添加事件侦听器,但是它会导致重复事件侦听器导致它两次触发一个函数。如果它已经存在,我该如何检查它以便我可以阻止它添加事件侦听器?

for (var a = 0;a<formFieldInput.length;a++) {
    if(formFieldInput[a].hasAttribute("name") && formFieldInput[a].attributes.title.value !== "Valid Until") {
        formFieldInput[a].addEventListener("click",function(event) {
            toggleFieldList(event,"show");
        });
    }

采纳答案by Ryan Warner

There is no JavaScript function to achieve this. However, you could set a boolean value to truewhen you add the listener, and falsewhen you remove it. Then check against this boolean before potentially adding a duplicate event listener.

没有 JavaScript 函数可以实现这一点。但是,您可以true在添加侦听器和false删除侦听器时设置一个布尔值。然后在可能添加重复的事件侦听器之前检查此布尔值。

Possible duplicate: How to check whether dynamically attached event listener exists or not?

可能重复:如何检查动态附加的事件侦听器是否存在?

回答by arufian

Nowadays (2016) in Chrome Dev Tools console, you can quickly execute this function below to show all event listeners that have been attached to an element.

现在(2016 年)在 Chrome Dev Tools 控制台中,您可以快速执行下面的此功能以显示已附加到元素的所有事件侦听器。

getEventListeners(document.querySelector('your-element-selector'));

回答by Ronnie Royston

You don't need to. Just slap it on there as many times as you want and as often as you want. MDN explains identical event listeners:

你不需要。只需按您想要的次数和次数将它贴在那里即可。MDN 解释了相同的事件侦听器

If multiple identical EventListeners are registered on the same EventTarget with the same parameters, the duplicate instances are discarded. They do not cause the EventListener to be called twice, and they do not need to be removed manually with the removeEventListenermethod.

如果在同一个 EventTarget 上使用相同的参数注册了多个相同的 EventListeners,则丢弃重复的实例。它们不会导致 EventListener 被调用两次,并且不需要使用该removeEventListener方法手动删除它们。