开发者

How can I bind all events on a DOM element?

How can I bind all events (开发者_如何学运维i.e. click, keypress, mousedown) on a DOM element, using jQuery, without listing each one out individually?

Example:

$('#some-el').bind('all events', function(e) {
    console.log(e.type);
});


there is a simple (but not accurate) way to test all events:

function getAllEvents(element) {
    var result = [];
    for (var key in element) {
        if (key.indexOf('on') === 0) {
            result.push(key.slice(2));
        }
    }
    return result.join(' ');
}

then bind all events like this:

var el = $('#some-el');
el.bind(getAllEvents(el[0]), function(e) {
    /* insert your code */
});


You also can redefine jQuery.event.trigger to catch each event, but, I think, this way is good only for exploring external API, not for production:

var oldJQueryEventTrigger = jQuery.event.trigger;
jQuery.event.trigger = function( event, data, elem, onlyHandlers ) { 
  console.log( event, data, elem, onlyHandlers ); 
  oldJQueryEventTrigger( event, data, elem, onlyHandlers ); 
}


Here's a small extension for jQuery:

$.fn.onAny = function(cb){
  for(var k in this[0])
    if(k.search('on') === 0)
      this.on(k.slice(2), function(e){
        // Probably there's a better way to call a callback function with right context, $.proxy() ?
        cb.apply(this,[e]);
      });
  return this;
};    

Usage:

$('#foo').onAny(function(e){
  console.log(e.type);
});  

Also you can just use browser console (from this answer):

monitorEvents($0, 'mouse'); // log all events of an inspected element
monitorEvents(document.body); // log all events on the body
monitorEvents(document.body, 'mouse'); // log mouse events on the body
monitorEvents(document.body.querySelectorAll('input')); // log all events on inputs


If you want to bind multiple events to the same function, simply separate them with spaces.

$("#test").bind("blur focus focusin focusout load resize scroll unload click " +
    "dblclick mousedown mouseup mousemove mouseover mouseout mouseenter " + 
     "mouseleave change select submit keydown keypress keyup error", function(e){
    $("#r").empty().text(e.type);
});

Simple example on jsfiddle


jQuery changed how it saves events, there's a couple ways to extract the list depending on which version you're using. I've encapsulated the "most recent" version in a plugin, but essentially you want:

var events = $._data($('yourelement')[0], "events");

This gives a nested list of all the bound events, grouped by the "base" event (no namespace).

However, I just realized you want all the native jQuery events - you could inspect $.event, which has some of them under $.event.special, but the accepted answer may still be your best bet. You can also look at what jQuery lists as possible binding functions.


I don't think jQuery supports any wildcard (it would be difficult and fraught with peril), but the list of standard events is finite (though sadly a bit spread out across the DOM2 events spec, the DOM2 HTML spec, and the DOM3 events spec), you could always simply list them. jQuery does allow you to give multiple event names to bind (space-delimited), e.g.:

$('#some-el').bind('click dblclick mouseover mouseout' /* etc.*/,function(e){
    console.log(e.type);
});


I have taken Mark Coleman's script and enhanced it a bit for my needs.

I would like to share it with you: http://jsfiddle.net/msSy3/65/

var lastEvent = null,
    countEvent = 0;
$("#test").bind("blur focus focusin focusout load resize scroll unload click" + " dblclick mousedown mouseup mousemove mouseover mouseout mouseenter " + "mouseleave change select submit keydown keypress keyup error", function (e) {
    if (lastEvent !== e.type) {
        countEvent++;
        $("#r").prepend("<span>" + countEvent + ": " + e.type + "<br></span>");
        $("#r > span:nth-child(21)").remove();
        lastEvent = e.type;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜