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

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

问题描述

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

Here is my problem: is it somehow possible to check for the existence of a dynamically attached event listener? Or how can I check the status of the "onclick" (?) property in the DOM? I have searched the internet just like Stack Overflow 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 a 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 在这里.如果您单击为 2 添加 onclick"然后是[link 2]",事件触发良好,但是测试链接 2"总是报错.有人可以帮忙吗?

jsFiddle is here. If you click "Add onclick for 2" and then "[link 2]", the 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天全站免登陆