问题描述
我需要捕捉一个事件,而不是让它冒泡。这就是我想要的:
I need to capture an event instead of letting it bubble. This is what I want:
<body>
<div>
</div>
</body>
从这个示例代码中,我在div和body上有一个click事件。我希望首先调用body事件。我该怎么做?
From this sample code I have a click event bounded on the div and the body. I want the body event to be called first. How do I go about this?
推荐答案
使用事件捕获代替: -
Use event capturing instead:-
$("body").get(0).addEventListener("click", function(){}, true);
默认情况下检查addEventListener的最后一个参数是false并处于事件冒泡模式。如果设置为true将作为捕获事件。
Check the last argument to "addEventListener" by default it is false and is in event bubbling mode. If set to true will work as capturing event.
用于跨浏览器实现。
var bodyEle = $("body").get(0);
if(bodyEle.addEventListener){
bodyEle.addEventListener("click", function(){}, true);
}else if(bodyEle.attachEvent){
document.attachEvent("onclick", function(){
var event = window.event;
});
}
IE8和先前默认情况下使用事件冒泡。所以我将事件附加到文档而不是正文,因此您需要使用事件对象来获取目标对象。对于IE,你需要非常棘手。
IE8 and prior by default use event bubbling. So I attached the event on document instead of body, so you need to use event object to get the target object. For IE you need to be very tricky.
这篇关于事件捕获jQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!