简体   繁体   中英

Finding events bound on non-existent elements

I'm planning to mercilessly re-factoring a lot of front-end code I have. Code has been added willy-nilly, features have been completely rewritten, and I know I've got a lot of events that are set up to listen on elements that don't exist.

Is there a way of finding code that attaches jQuery events to non-existent elements? Was hoping to find events that aren't used anymore without going through all the code manually.

A possible debugging step is to override the on method with a debug version as shown below. It will list event registration attempts where the element set is empty and the trace for locating the code.

(function(){
    var old = $.fn.each;
    $.fn.each = function(){
        if(this.length == 0){
            console.debug('non-selector', this.selector)
            console.trace()
        }
        return old.apply(this, arguments);
    }
})();

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM