jQuery 如何绑定 DOM 元素上的所有事件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5848598/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:54:27  来源:igfitidea点击:

How can I bind all events on a DOM element?

jqueryjavascript-events

提问by Yosef

How can I bind all events (i.e. click, keypress, mousedown) on a DOM element, using jQuery, without listing each one out individually?

如何使用 jQuery绑定DOM 元素上的所有事件(即click, keypress, mousedown),而不单独列出每个事件?

Example:

例子:

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

采纳答案by otakustay

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 */
});

回答by Leonid Shagabutdinov

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:

您也可以重新定义 jQuery.event.trigger 来捕获每个事件,但是,我认为,这种方式仅适用于探索外部 API,不适用于生产:

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

回答by drzaus

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

jQuery 改变了它保存事件的方式,有几种方法可以根据您使用的版本来提取列表。我已经将“最新”版本封装在一个插件中,但基本上你想要:

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 answermay still be your best bet. You can also look at what jQuery lists as possible binding functions.

但是,我刚刚意识到您想要所有本机 jQuery 事件 - 您可以检查$.event,其中有一些在 下$.event.special,但接受的答案可能仍然是您最好的选择。您还可以查看jQuery 列出哪些可能的绑定函数

回答by Mark Coleman

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

jsfiddle 上的简单示例

回答by mu3

Here's a small extension for jQuery:

这是 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(
$('#some-el').bind('click dblclick mouseover mouseout' /* etc.*/,function(e){
    console.log(e.type);
});
, '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

回答by T.J. Crowder

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.:

我不认为 jQuery 支持任何通配符(这会很困难并且充满危险),但是标准事件列表是有限的(尽管遗憾的是有点分散在DOM2 事件规范DOM2 HTML 规范DOM3 事件中spec),你总是可以简单地列出它们。jQuery 确实允许您提供多个要绑定的事件名称(以空格分隔),例如:

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;
    }
});

回答by DaviideSnow

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

我采用了 Mark Coleman 的脚本并根据我的需要对其进行了一些增强。

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

我想与你分享:http: //jsfiddle.net/msSy3/65/

##代码##