如何检查动态连接的事件监听器是否存在? [英] How to check whether dynamically attached event listener exists or not?

查看:777
本文介绍了如何检查动态连接的事件监听器是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的问题:是否有可能以某种方式检查是否存在动态附加的事件监听器?或者我如何检查DOM中onclick(?)属性的状态?我已经像StackOverflow一样搜索了互联网,但是没有运气。这是我的html:

Here is my problem: is it possible somehow to check for existence of dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in DOM? I have searched internet just like StackOverflow for a solution, but no luck. Here is my html:

<a id="link1" onclick="linkclick(event)"> link 1 </a>
<a id="link2"> link 2 </a> <!-- without inline onclick handler -->

然后在javascript中我将动态创建的事件监听器附加到第二个链接:

Then in javascript I attach dynamically created event listener to the 2nd link:

document.getElementById('link2').addEventListener('click', linkclick, false);

代码运行良好,但我检测连接侦听器的所有尝试都失败了:

The code runs well, but all my attempts to detect that attached listener fail:

// test for #link2 - dynamically created eventlistener
alert(elem.onclick); // null
alert(elem.hasAttribute('onclick')); // false
alert(elem.click); // function click(){[native code]} // btw, what's this?

jsFiddle在这里
如果你点击添加onclick for 2然后[link 2],事件就会激活,
但是测试链接2总是报告错误。
有人可以帮忙吗?

jsFiddle is here. If you click "Add onclick for 2" and then "[link 2]", event fires well, but the "Test link 2" always reports false. Can somebody help?

推荐答案

无法检查动态连接的事件监听器是否存在。

There is no way to check whether dynamically attached event listeners exist or not.

你可以看到附加事件监听器的唯一方法是附加这样的事件监听器:

The only way you can see if an event listener is attached is by attaching event listeners like this:

elem.onclick = function () { console.log (1) }

然后您可以通过返回 !! elem.onclick 来测试事件监听器是否附加到 onclick (或者类似的东西)。

You can then test if an event listener was attached to onclick by returning !!elem.onclick (or something similar).

这篇关于如何检查动态连接的事件监听器是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆