How to find event listeners on a DOM node when debugging or from the JavaScript code?

前端 未结 19 2543
臣服心动
臣服心动 2020-11-21 05:34

I have a page where some event listeners are attached to input boxes and select boxes. Is there a way to find out which event listeners are observing a particular DOM node a

19条回答
  •  终归单人心
    2020-11-21 06:14

    (Rewriting the answer from this question since it's relevant here.)

    When debugging, if you just want to see the events, I recommend either...

    1. Visual Event
    2. The Elements section of Chrome's Developer Tools: select an element and look for "Event Listeners" on the bottom right (similar in Firefox)

    If you want to use the events in your code, and you are using jQuery before version 1.8, you can use:

    $(selector).data("events")
    

    to get the events. As of version 1.8, using .data("events") is discontinued (see this bug ticket). You can use:

    $._data(element, "events")
    

    Another example: Write all click events on a certain link to the console:

    var $myLink = $('a.myClass');
    console.log($._data($myLink[0], "events").click);
    

    (see http://jsfiddle.net/HmsQC/ for a working example)

    Unfortunately, using $._data this is not recommended except for debugging since it is an internal jQuery structure, and could change in future releases. Unfortunately I know of no other easy means of accessing the events.

提交回复
热议问题