我试图找到这个JavaScript方法调用的jQuery等价:
document.addEventListener('click', select_element, true);
我已经说到:
$(document).click(select_element);
但这并不能达到相同的结果,因为JavaScript方法的最后一个参数——一个布尔值,它指示事件处理程序应该在捕获阶段还是冒泡阶段执行(根据我从http://www.quirksmode.org/js/events_advanced.html的理解)——被省略了。
我如何指定该参数,或以其他方式实现相同的功能,使用jQuery?
下面是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);