禁用href的点击传播

时间:2017-07-08 10:27:49

标签: javascript jquery html css

此代码段解释了我的案例:

$("#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的点击功能,而不是href标记的a。在类似的问题中,我发现event.stopPropagation(),但在这种情况下不起作用。

3 个答案:

答案 0 :(得分:3)

您需要使用event.preventDefault()方法阻止默认点击事件操作。

&#13;
&#13;
$("#b").click(function(e) {
  e.preventDefault();
  alert("trigger div");
});
&#13;
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;
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

$("#a").click(function (event) {
    event.preventDefault();
});

$("#b").click(function (event) {
    event.stopPropagation();
    alert("trigger div");
});

答案 2 :(得分:1)

没有javascript:

#a {
  display: block;
  position: absolute;
  width: 100px;
  height: 100px;
  background-color: gray;
}

div {
  position: absolute;
  width: 50px;
  height: 50px;
  background-color: red;
}
<a href="stackoverflow.com" id="a">
<a href="#"><div onclick="alert('trigger div')">test</div></a>
</a>