我的网页上有以下设置
<div id="clickable">
<a href="hello.com">Here!</a>
</div>
有没有办法可以避免触发div的click事件。我认为它与在锚点标签的onclick
属性中设置某些内容有关,但尝试像e.preventDefault()
之类的简单操作却无效。
帮助?谢谢!
答案 0 :(得分:10)
e.preventDefault();不会在onclick属性中工作,因为e未定义。还有e.preventDefault();不希望你想停止冒泡,你需要e.stopPropagation();
使用;
onclick="$(this).stopPropagation();"
在您的锚上,或
$(a).click(function(e){
e.stopPropagation();
});
在你的活动中。
答案 1 :(得分:3)
e.preventDefault()
并不会阻止事件冒泡。您需要添加e.stopPropagation()
,或将其替换为return false
。
您可以在differences between these three in this answer上阅读更多内容。
答案 2 :(得分:1)
您可以使用onclick =“return false;”
<a href="#" onclick="return false;">stuff</a>
答案 3 :(得分:0)
您可以return false;
或确保您的函数使用e
作为参数
$("#clickable a").click(function(e){
//stuff
e.preventDefault;
});
答案 4 :(得分:0)
Vanilla JS扩展已接受的答案。 event.stopPropagation()
是防止事件冒泡到父容器而不禁用默认行为的最具体且可预测的方法。在以下示例中,<a/>
不会触发警报,即使它包含在可点击的<div/>
中。
<script>
function linkHandler(event) {
event.stopPropagation()
}
</script>
<div onclick="alert('fail)">
<a href="http://stackoverflow.com" onclick="linkHandler(event)">Link</a>
</div>