我想在我的HTML中阻止父级
向子级
传播事件。这是我尝试做的简单代码:
<div>
<div id='categoryList'>
<div class='listed-category'>
<span>some content</span>
<a id='close'>x</a> //"a" is used to remove the div
</div>
</div>
</div>
<div id='dropdown'>
</div>
如果我点击上面代码中的<div id='categoryList'>
,那么下面的代码将使<div id='dropdown'>
上下滑动。
$(document).ready(function () {
$('#categoryList').click(function (event) {
event.preventDefault();
event.stopPropagation();
if ($('#dropdown').is(":visible")) {
$('#dropdown').slideUp(400);
}
else {
$('#dropdown').slideDown(400);
}
});
})
但是当我点击子元素<div class='listed-category'>
时,上面的JavaScript会执行,导致<div id='dropdown'>
向上或向下滑动。如何停止这个操作?但我仍然想能够点击<a id='close'>
来删除子元素div
。
event.target !== event.currentTarget
而不是this
,因为this
的上下文可能会被重新绑定。 - Ezio_