Can I find events bound on an element with jQuery?

前端 未结 9 1937
南旧
南旧 2020-11-22 07:11

I bind two event handlers on this link:

Show Alert

JavaScript:

$(         


        
相关标签:
9条回答
  • 2020-11-22 07:46

    I'm adding this for posterity; There's an easier way that doesn't involve writing more JS. Using the amazing firebug addon for firefox,

    1. Right click on the element and select 'Inspect element with Firebug'
    2. In the sidebar panels (shown in the screenshot), navigate to the events tab using the tiny > arrow
    3. The events tab shows the events and corresponding functions for each event
    4. The text next to it shows the function location

    0 讨论(0)
  • 2020-11-22 07:47

    In modern versions of jQuery, you would use the $._data method to find any events attached by jQuery to the element in question. Note, this is an internal-use only method:

    // Bind up a couple of event handlers
    $("#foo").on({
        click: function(){ alert("Hello") },
        mouseout: function(){ alert("World") }
    });
    
    // Lookup events for this particular Element
    $._data( $("#foo")[0], "events" );
    

    The result from $._data will be an object that contains both of the events we set (pictured below with the mouseout property expanded):

    Console output for $._

    Then in Chrome, you may right click the handler function and click "view function definition" to show you the exact spot where it is defined in your code.

    0 讨论(0)
  • 2020-11-22 07:48

    Note that events may be attached to the document itself rather than the element in question. In that case, you'll want to use:

    $._data( $(document)[0], "events" );
    

    And find the event with the correct selector:

    And then look at the handler > [[FunctionLocation]]

    0 讨论(0)
  • 2020-11-22 07:49

    You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().

    For example type the following in the dev tools console:

    // Get all event listners bound to the document object
    getEventListeners(document);
    
    0 讨论(0)
  • 2020-11-22 07:49

    When I pass a little complex DOM query to $._data like this: $._data($('#outerWrap .innerWrap ul li:last a'), 'events') it throws undefined in the browser console.

    So I had to use $._data on the parent div: $._data($('#outerWrap')[0], 'events') to see the events for the a tags. Here is a JSFiddle for the same: http://jsfiddle.net/giri_jeedigunta/MLcpT/4/

    0 讨论(0)
  • 2020-11-22 07:55

    The jQuery Audit plugin plugin should let you do this through the normal Chrome Dev Tools. It's not perfect, but it should let you see the actual handler bound to the element/event and not just the generic jQuery handler.

    0 讨论(0)
提交回复
热议问题