I am looking for a way to list all elements that have onclick
event on a page.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
For a succinct jquery selector, you could use
$('[onclick]')
however that would only get elements wit the onclick attribute set.This is fairly easy if the traditional/old school method of event handler attachment is used (the following code is untested).
Use:
Answer from @Josh the Goods didn't work for me, I had to slightly modify it.
You can read the string value of the
onclick
attribute by using:inside Josh's code (this is a slightly roundabout method, required for IE).
Of course it would only work for event handlers attached from inline event handler attributes, not assigned to the
onclick
property from JavaScript or added viaaddEventListener
orattachEvent
.Trying to prise values out of a JavaScript code string is an ugly and unreliable hack that you shouldn't resort to unless there's really no other option. If the page is something you're generating yourself, you should instead use unobtrusive-scripting techniques. Omit inline event handler attributes like
onclick
completely (today they're considered bad practice) and attach handlers from JavaScript itself, using parameters stored in easier-to-access places like classname and other ‘spare’ attributes where necessary.Edited to answer further questions...
I'm not sure exactly what you're asking, but I suspect you're looking for a way to see if there has been code attached to an element's onclick event? If so, try this:
If you'd like some information about the actual function attached to the onclick event, you'll need to make use of Firebug or something similar to output the function and examine it as it will have been possibly generated at runtime (ie the function declaration might not just be sitting on the page where it could theoretically be accessed easily). Try using the code provided above, but instead of
do
Now, in firebug, you can mouse over the functions it prints and see their code.
If you use jQuery >= 1.4, you can get an Array of all elements with onclick attribute by writing the oneliner: