问题
Say you have this div:
<div id="foo">bar</div>
And you do this:
$("#foo").click(someFunction);
somewhere inside your javascript code.
Once the page has been loaded, is there a way to find out, via firebug or inspect element in chrome, or anything else, that the click event for #foo is bound to someFunction
? I.e, find this out without having to look through all your code?
回答1:
Chrome Developer tools does this.
- right click an element
- click inspect element
- in the right hand column, scroll down to event listeners
This will give you a list of event listeners on the object that can be expanded to find their source and the attached function.
Firebug has this information under the DOM tab, but it's less user friendly.
回答2:
You can use the console in browsers built-in developer tools. They are built-in for IE and Chrome while FF will need the Firebug AddOn installed. I don't know about other browsers.
Using the debugger console you can use jQuery data("events")
to query for the attached events of an element. In addition those consoles also let you dynamically drill down into any additional detail of the events you are interested in.
$("#foo").data("events");
Executing the above in the console will display an object with a property for each event it found. In your example it returns an object with click
property of type array storing all click events.
If you have click events and you want just that object you can execute the following in the console:
$("#foo").data("events").click;
Each event object has a handler
property which will show you the function they are bound to:
Object
data: null
guid: 2
handler: function mytestFunction(){
arguments: null
caller: null
guid: 2
length: 0
name: "mytestFunction"
prototype: mytestFunction
__proto__: function Empty() {}
namespace: ""
origType: "click"
quick: null
selector: null
type: "click"
__proto__: Object
See DEMO, showing how to query and display the objects in the console.
Alternatively you can also use the "handlers" for an overall summary object:
$("#foo").data("handlers");
Note though that .data("events/handlers")
will not include any events wired up embedded in html such as this:
<div id="foo" onclick="...">bar</div>
More information on the data()
are in the documentation
回答3:
I don't know about Firefox, but there's an easy way to see event listeners in Chrome and Safari. Just open the Developer Tools, select your element and scroll to the bottom of the CSS properties panel. You'll find an "Event Listeners" section.
回答4:
I would suggest using Visual Event 2
.
Here is the description on how to use it. I use it almost everyday and its a very good tool.
来源:https://stackoverflow.com/questions/11863400/is-there-a-way-to-find-the-event-handlers-of-an-element-with-javascript