How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

前端 未结 15 1376
一个人的身影
一个人的身影 2020-11-22 06:56

I need to debug a web application that uses jQuery to do some fairly complex and messy DOM manipulation. At one point, some of the events that were bound to particular eleme

15条回答
  •  一个人的身影
    2020-11-22 07:37

    Here's a plugin which can list all event handlers for any given element/event:

    $.fn.listHandlers = function(events, outputFunction) {
        return this.each(function(i){
            var elem = this,
                dEvents = $(this).data('events');
            if (!dEvents) {return;}
            $.each(dEvents, function(name, handler){
                if((new RegExp('^(' + (events === '*' ? '.+' : events.replace(',','|').replace(/^on/i,'')) + ')$' ,'i')).test(name)) {
                   $.each(handler, function(i,handler){
                       outputFunction(elem, '\n' + i + ': [' + name + '] : ' + handler );
                   });
               }
            });
        });
    };
    

    Use it like this:

    // List all onclick handlers of all anchor elements:
    $('a').listHandlers('onclick', console.info);
    
    // List all handlers for all events of all elements:
    $('*').listHandlers('*', console.info);
    
    // Write a custom output function:
    $('#whatever').listHandlers('click',function(element,data){
        $('body').prepend('
    ' + element.nodeName + ':
    ' + data + '<\/pre>');
    });
    

    Src: (my blog) -> http://james.padolsey.com/javascript/debug-jquery-events-with-listhandlers/

提交回复
热议问题