event.stopPropagation()和event.stopImmediatePropagation()有什么不同
发布于 2011-03-14 22:19:21
stopPropagation将阻止执行任何父处理程序stopImmediatePropagation将阻止任何父处理程序以及任何其他处理程序执行
jquery documentation:中的快速示例
$("p").click(function(event) {
event.stopImmediatePropagation();
});
$("p").click(function(event) {
// This function won't be executed
$(this).css("background-color", "#f00");
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>example</p>
注意,事件绑定的顺序在这里很重要!
$("p").click(function(event) {
// This function will now trigger
$(this).css("background-color", "#f00");
});
$("p").click(function(event) {
event.stopImmediatePropagation();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>example</p>
发布于 2012-03-27 06:37:40
一个小示例来演示这两个传播中断是如何工作的。
var state = {
stopPropagation: false,
stopImmediatePropagation: false
};
function handlePropagation(event) {
if (state.stopPropagation) {
event.stopPropagation();
}
if (state.stopImmediatePropagation) {
event.stopImmediatePropagation();
}
}
$("#child").click(function(e) {
handlePropagation(e);
console.log("First event handler on #child");
});
$("#child").click(function(e) {
handlePropagation(e);
console.log("Second event handler on #child");
});
// First this event will fire on the child element, then propogate up and
// fire for the parent element.
$("div").click(function(e) {
handlePropagation(e);
console.log("Event handler on div: #" + this.id);
});
// Enable/disable propogation
$("button").click(function() {
var objectId = this.id;
$(this).toggleClass('active');
state[objectId] = $(this).hasClass('active');
console.log('---------------------');
});div {
padding: 1em;
}
#parent {
background-color: #CCC;
}
#child {
background-color: #000;
padding: 5em;
}
button {
padding: 1em;
font-size: 1em;
}
.active {
background-color: green;
color: white;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
<div id="child"> </div>
</div>
<button id="stopPropagation">Stop Propogation</button>
<button id="stopImmediatePropagation" ">Stop Immediate Propogation</button>
绑定了三个事件处理程序。如果我们不停止任何传播,那么应该有四个警报-三个在子div上,一个在父div上。
如果我们停止事件的传播,那么将会有3个警报(都在内层的子div上)。因为事件不会在DOM层次结构中向上传播,所以父div看不到它,它的处理程序也不会触发。
如果我们立即停止传播,那么将只有一个警报。即使有三个事件处理程序附加到内部的子div,也只执行一个,并且任何进一步的传播都会立即终止,即使在同一个元素中也是如此。
发布于 2011-03-14 22:14:20
从jQuery API
除了阻止执行元素上的任何其他处理程序外,此方法还通过隐式调用event.stopPropagation()来停止冒泡。为了简单地防止事件冒泡到祖先元素,但允许其他事件处理程序在同一元素上执行,我们可以使用event.stopPropagation()。
使用event.isImmediatePropagationStopped()来了解是否(在该事件对象上)调用过此方法。
简而言之:event.stopPropagation()允许执行同一元素上的其他处理程序,而event.stopImmediatePropagation()则阻止每个事件运行。
https://stackoverflow.com/questions/5299740
复制相似问题