jQuery find events handlers registered with an object

后端 未结 16 3117
予麋鹿
予麋鹿 2020-11-21 07:16

I need to find which event handlers are registered over an object.

For example:

$(\"#el\").click(function() {...});
$(\"#el\").mouseover(function() {         


        
16条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 07:52

    I created a custom jQuery selector that checks against both jQuery's cache of assigned event handlers as well as elements that use the native method for adding them:

    (function($){
    
        $.find.selectors[":"].event = function(el, pos, match) {
    
            var search = (function(str){
                if (str.substring(0,2) === "on") {str = str.substring(2);}
                return str;
            })(String(match[3]).trim().toLowerCase());
    
            if (search) {
                var events = $._data(el, "events");
                return ((events && events.hasOwnProperty(search)) || el["on"+search]);
            }
    
            return false;
    
        };
    
    })(jQuery);
    

    Example:

    $(":event(click)")
    

    This will return elements that have a click handler attached to them.

提交回复
热议问题