此代码片段解释了我的情况:
$("#b").click(function(e) {
e.stopPropagation();
});
$("#b").click(function() {
alert("trigger div");
});
a {
display: block;
position: relative;
width: 100px;
height: 100px;
background-color: gray;
}
div {
position: absolute;
width: 50px;
height: 50px;
top: 0;
left: 0;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="stackoverflow.com" id="a">
<div id="b">Test</div>
</a>
问题是我只想触发 div
的点击功能,而不是 a
标签的 href
。在类似的问题中,我找到了 event.stopPropagation()
,但在这种情况下不起作用。
最佳答案
您需要使用 event.preventDefault()
来阻止默认的点击事件操作方法。
$("#b").click(function(e) {
e.preventDefault();
alert("trigger div");
});
a {
display: block;
position: relative;
width: 100px;
height: 100px;
background-color: gray;
}
div {
position: absolute;
width: 50px;
height: 50px;
top: 0;
left: 0;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="stackoverflow.com" id="a">
<div id="b">Test</div>
</a>
关于javascript - 禁用 href 的点击传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44985147/