如果用户单击特定的子元素,我想阻止我的父级单击方法触发。
示例 html:
<div data-type="parent_holder" style="width:500px; height:500px;">
<div data-type="child_holder" style="width:50px; height:50px; position:absolute;">
click
</div>
</div>
示例 js:
我在 js 中使用 jquery,因为我将元素动态附加到可排序列表。
$( "#sortable" ).on( "click", "[data-type=parent_holder]", function() {
alert('parent');
});
$( "#sortable" ).on( "click", "[data-type=child_holder]", function() {
alert('child');
});
所以我想要的是,当用户点击parent_holder时,它应该提醒 parent ,但是如果用户点击child_holder,它应该提醒 child ,而不是提醒 parent 。
我搜索了 stackoverflow,并尝试了很多建议,例如 :not()、冒泡、stopPropagation(),但我似乎无法得到正确的结果。
最佳答案
听起来您的情况正在发生事件传播,
只需使用 event.stopPropagation()
尝试,
$( "#sortable" ).on( "click", "[data-type=child_holder]", function(e) {
e.stopPropagation();
alert('child');
});
DEMO
关于javascript - 如果单击特定子项,则防止触发父级单击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23826915/