我试图找到这个JavaScript方法调用的jQuery等价:

document.addEventListener('click', select_element, true);

我已经说到:

$(document).click(select_element);

但这并不能达到相同的结果,因为JavaScript方法的最后一个参数——一个布尔值,它指示事件处理程序应该在捕获阶段还是冒泡阶段执行(根据我从http://www.quirksmode.org/js/events_advanced.html的理解)——被省略了。

我如何指定该参数,或以其他方式实现相同的功能,使用jQuery?


最接近的是bind函数:

http://api.jquery.com/bind/

$('#foo').bind('click', function() {
  alert('User clicked on "foo."');
});

并非所有浏览器都支持事件捕获(例如,Internet Explorer 9以下版本不支持),但所有浏览器都支持事件冒泡,这就是为什么在包括jQuery在内的所有跨浏览器抽象中,冒泡是用于将处理程序绑定到事件的阶段。

在jQuery中,最接近你所寻找的是使用bind()(在jQuery 1.7+中被on()取代)或特定于事件的jQuery方法(在本例中是click(),它在内部调用bind())。都使用引发事件的冒泡阶段。


从jQuery 1.7开始,.on()现在是绑定事件的首选方法,而不是.bind():

从http://api.jquery.com/bind/:

从jQuery 1.7开始,.on()方法是 将事件处理程序附加到文档。对于较早的版本, .bind()方法用于将事件处理程序直接附加到 元素。中的当前选定元素附加处理程序 jQuery对象,所以这些元素必须存在于调用点 发生.bind()。有关更灵活的事件绑定,请参阅讨论部分 .on()或.delegate()中的事件委托。

文档页面位于 http://api.jquery.com/on/


现在应该使用.on()函数来绑定事件。


下面是Mozilla开发网络(MDN)上关于标准JavaScript问题的一个很好的处理(如果你不希望依赖jQuery或更好地理解它):

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

下面是来自上述处理中的一个链接的事件流的讨论:

http://www.w3.org/TR/DOM-Level-3-Events/#event-flow

一些要点是:

It allows adding more than a single handler for an event It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling) It works on any DOM element, not just HTML elements The value of "this" passed to the event is not the global object (window), but the element from which the element is fired. This is very convenient. Code for legacy IE browsers is simple and included under the heading "Legacy Internet Explorer and attachEvent" You can include parameters if you enclose the handler in an anonymous function


需要注意的一点是,jQuery事件方法不会在包含SVG DOM的嵌入标记上触发/捕获加载,SVG DOM在嵌入标记中作为单独的文档加载。我发现捕获加载事件的唯一方法是使用原始JavaScript。

这将不起作用(我已经尝试了/bind/load方法):

$img.on('load', function () {
    console.log('FOO!');
});

然而,这是可行的:

$img[0].addEventListener('load', function () {
    console.log('FOO!');
}, false);

$(“按钮”)。On(“点击”,函数(事件){ Alert ($(this).html()); console.log(事件。目标); }); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js " > < /脚本> < >按钮测试1 > < /按钮 < >按钮测试2 > < /按钮