检查一个元素是否有事件侦听器

如果我像下面的代码一样在元素上使用内联函数,如何检查元素是否有事件侦听器?因为我有一个函数可以回忆这个函数并添加事件侦听器,但是它会导致重复事件侦听器,从而导致它触发一个函数两次。如果事件侦听器已经存在,我如何检查它以防止它添加事件侦听器?

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");
});
}
201148 次浏览

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

可能是复制品: How to check whether dynamically attached event listener exists or not?

Since 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.

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

免责声明 : 此解决方案仅适用于 铬合金开发人员工具。

你不需要知道。你想涂多少次就涂多少次。返回文章页面

如果在相同的 具有相同参数的 EventTarget,重复的实例是 discarded. They do not cause the EventListener to be called twice, and 它们不需要用 removeEventListener手动删除 方法。

但是请注意,当使用匿名函数时作为处理程序,这样的侦听器不会是相同的,因为即使使用重复调用的 SAME 不变源代码定义匿名函数,即使在循环中,也不会是相同的。