Javascript事件冒泡 [英] Javascript Event Bubbling
问题描述
我有这个设置
<div onclick="SomeEvent">
<input type=checkbox value=1>1
<input type=checkbox value=2>2
<input type=checkbox value=3>3
</div>
当用户点击复选框时我不希望SomeEvent被触发的问题。
The problem when the user click on the checkboxes I don't want the SomeEvent fired.
在某些情况下,我确实有一行
event.stopPropagation();
但似乎什么都不做。
In the some event I do have the line
"event.stopPropagation();"
but that seems to do nothing at all.
推荐答案
在事件冒泡模型中,事件传播来自内部元素到外部元素。
In the event bubbling model, the event propagation is from the inner elements to the outer elements.
这意味着 event.stopPropagation(); 应该在输入'事件而不是div中。
This means that the event.stopPropagation(); should be in the inputs' events instead of the div.
<div onclick="SomeEvent">
<input type=checkbox value=1 onclick="stopPropagation()">1
<input type=checkbox value=2 onclick="stopPropagation()>2
<input type=checkbox value=3 onclick="stopPropagation()>3
</div>
现在的Javascript代码:
Now the Javascript code:
function stopPropagation() {
//... do something.
//stop propagation:
if (!e) var e = window.event;
e.cancelBubble = true; //IE
if (e.stopPropagation) e.stopPropagation(); //other browsers
}
更多信息:http://www.quirksmode.org/js/events_order.html
编辑:以上是显示冒泡模型如何工作的快速方法,但使用JQuery解决此问题的更好答案是:
EDIT: The above was a quick way to show how the bubbling model works, but a better answer to solve this problem using JQuery would be:
<div id="mydiv">
<input type="checkbox" value="1" /> 1
<input type="checkbox" value="2" /> 2
<input type="checkbox" value="3" /> 3
</div>
现在的Javascript代码:
Now the Javascript code:
$('#mydiv').click(function(e) {
//do something
});
$('#mydiv input').click(function(e) {
//stop propagation:
if (!e) var e = window.event;
e.cancelBubble = true; //IE
if (e.stopPropagation) e.stopPropagation(); //other browsers
});
这篇关于Javascript事件冒泡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!