简体   繁体   English

jQuery检查元素上是否存在onClick

[英]jQuery check if onClick exists on element

I found the way to check if event exists on element . 我找到了检查event是否存在于element上的方法 But it's not work on the events which is not delegated by jQuery... 但这不适用于未由jQuery委托的事件...

When I try, 当我尝试的时候

$("a").data("events");

for this. 为了这。

<a href="#" onClick="alert('Hello, World!')" />

It returned undefined. 它返回未定义。

Is there any way to check if onClick exists on elements with jQuery? 有什么方法可以检查jQuery元素上是否存在onClick

Thanks. 谢谢。

你可以做:

if ($('a').attr("onClick") != undefined) {}

Just do: 做就是了:

if( myelement.onclick != null )
{
   //onclick exists
}
else
{
   //onclick doesn't exist
}

No need for jQuery. 不需要jQuery。

if( $('#elementName').click == undefined)  
   { //event handler doesn't exist }
else 
   { //handler exists }

For sure there are some valid answers here, this was a good one that got me going. 可以肯定的是,这里有一些有效的答案,这是一个很好的答案。

if ($('a').attr("onClick") != undefined) {}

But I found the best answer for you, as it was for since we are both dealing with hyperlinks, would looking for the href attribute. 但是我发现了最适合您的答案,因为这是因为我们俩都在处理超链接,所以会寻找href属性。

if ($('a').attr("href") != undefined) {}

I particularly liked this approach. 我特别喜欢这种方法。

I think the following things should also work 我认为以下事情也应该起作用

if ($(yourElement).attr("onClick").length != 0) {}

if ($(yourElement).attr("onClick").size() != 0) {}

Thanks 谢谢

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

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