是的。在大多数标准的浏览器,你在事件对象上调用stopPropagation
(live example | source):
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); event.stopPropagation();">Tha button</button>, Click me!
</div>
在IE浏览器的较旧的副本,您必须将cancelBubble
属性设置为true
代替:
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); event.cancelBubble = false;">Tha button</button>, Click me!
</div>
。 ..这意味着为了广泛的兼容性,你必须测试你正在处理哪个,哪个变得丑陋(live example | source):
<div onclick="alert('Hi, from outer div!');">
<button onclick="alert('Hi, from button!'); if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; }">Tha button</button>, Click me!
</div>
个
这些各种各样的差别,为什么我总是建议移动从旧DOM0式处理掉,并使用一个体面的JavaScript库,例如jQuery,Prototype,YUI,Closure,或any of several others。这些平滑的浏览器之间的差异,并提供了大量的实用功能。
例如,使用jQuery,这个HTML:
<div id="theDiv">
<button id="theButton">Tha button</button>, Click me!
</div>
...这脚本(live example | source):
$("#theDiv").click(function() {
alert('Hi, from outer div!');
});
$("#theButton").click(function(event) {
alert('Hi, from button!');
event.stopPropagation(); // Even on IE, jQuery provides this
});
或经常使用jQuery,你看人家只是做return false;
在其事件处理程序中。处理器中的return false;
,jQuery中的,会做两件事:停止传播,并阻止事件可能具有的任何默认操作(例如,在链接上的点击处理程序中)。 stopPropgation
不会阻止默认设置。
但这并不意味着是jQuery的广告(虽然它是一个非常好的库)。关闭,YUI,Prototype和其他所有其他类似的功能让你不用担心浏览器的这些不兼容问题。
你可能想[初级](http://www.quirksmode.org/js/events_order.html)为初学者 – Joseph 2012-03-30 09:42:18
可能的重复[防止父容器点击事件从点击超链接时发射](http://stackoverflow.com/questions/1997084/prevent-parent-container-click-event-from-firing-when-hyperlink-clicked)...看看最高的投票答案,而不是(如果你不使用jQuery)。 – 2012-03-30 09:42:47
@FelixKling,我正在使用没有处理程序的1级dom事件,这可能是一个很大的区别... – 2012-03-30 09:43:43