Jquery 如何为div的子级避免onclick事件
我正在移动一个被点击的DIV,这很有效。但是DIV包含表单元素,并且在单击它们时也会发生动作,这是我不希望看到的 我尝试向DIV的所有子级添加一个函数,该函数被调用,但父onclick仍然被触发Jquery 如何为div的子级避免onclick事件,jquery,Jquery,我正在移动一个被点击的DIV,这很有效。但是DIV包含表单元素,并且在单击它们时也会发生动作,这是我不希望看到的 我尝试向DIV的所有子级添加一个函数,该函数被调用,但父onclick仍然被触发 $("#ControlPanel").click(function() { switch ( $(this).css("top") ) { case "0px": $(this).animate({ top: "-100px" }); brea
$("#ControlPanel").click(function() {
switch ( $(this).css("top") )
{
case "0px":
$(this).animate({ top: "-100px" });
break;
case "-100px":
$(this).animate({ top: "0px" });
break;
}
});
$("#ControlPanel").children().click(function() { alert(1); return; });
我决定:
$("#ControlPanel").click(function(event) {
if ( event.target == "[object HTMLDivElement]") {
switch ( $(this).css("top") )
{
case "0px":
$(this).animate({ top: "-100px" });
break;
case "-100px":
$(this).animate({ top: "0px" });
break;
}
}
});
您只需要停止通过DOM向上传播的单击事件,这可以使用
stopPropagation()
方法实现。请参阅此JSFIDLE以演示:
.children().click(function(event){
event.stopPropagation();
});