防止执行父事件处理程序
问题描述:
我有一棵div树:
<div id="a" onclick="func">
<div id="b" onclick="func">
<div id="c" onclick="func">
</div>
</div>
</div>
当对div进行点击时,它会让孩子看不见 - 即点击a将转b和c不可见。
When a click is made on a div it makes it's children invisible - ie click on "a" will turn "b" and "c" invisible.
function func{
if ($(childId).hasClass("visible")){
$(childId).removeClass("visible");
$(childId).addClass("invisible");
}
问题是:点击b会调用a'单击并使b和c不可见。如何禁用使用jQuery点击a?
The problem is: a click on "b" will call "a"'s click and make "b" and "c" invisible. How do I disable the click on "a" using jQuery?
谢谢
答
您可以为子项添加一个处理程序,以阻止Click事件向上传播:
You can add a handler for the child that will prevent the click event from propagating up:
function handler(event) {
event.stopPropagation();
// now do your stuff
}
$('#a').add('#b').click(handler);
这样点击'#b'
不会传播到'#a'
。也不会点击'#c'
转到'#b'
,因此不会'#a'
。
This way clicks to '#b'
will not propagate to '#a'
. Neither will clicks to '#c'
go to '#b'
, and hence not to '#a'
.