stopPropagation() and anchor?

stopPropagation() and anchor?

本文关键字:anchor and stopPropagation      更新时间:2023-09-26

我有这样的html片段:

<a href="picture-big.jpg">
  <span>
    <img src="picture-small.jpg">
    <input type="checkbox" name="delete">
  </san>
</a>

和JS部分:

$('input').click(function(e) {
  e.stopPropagation();
}); 

在Mozilla上,当我点击复选框时,它会停止传播,但仍然会到达锚点(picture-big.jpg)。

如果我使用返回false或e.p preventdefault()(和jQuery ($('input')检查复选框)。Prop ('checked', true);)不检查输入。

的想法是勾选复选框没有以下链接。在Chrome和IE上,它是工作的。但在Mozilla上不是这样。

任何想法?

我建议重新构建你的标记,如果这是不可能的,下面将工作:

$('input').click(function(e) {
    e.preventDefault();
    var that = this;    
    setTimeout(function() { that.checked = !that.checked; }, 1);    
}); 

小提琴

stopPropagation()只是阻止事件在dom树中冒泡,这意味着父母不会收到通知,但它不会阻止默认操作的发生。您需要在代码中添加e.preventDefault()来阻止它导航。

这是一个已知的Firefox bug。一开始,我试着用JavaScript的方式解决了很长一段时间,直到我意识到什么应该是显而易见的方法:

我可以更容易地改变html结构。我在锚中嵌套了一个复选框。由于锚是绝对定位在相对div内的,因此它立即起作用。

<input type="checkbox" name="delete">
<a href="picture-big.jpg">
</a>

老问题,但如果有人需要答案。因此,如果你不能改变外部锚标记,你可以自己包装复选框,例如:

<a href="javascript:void(0);">
   <input type="checkbox">
</a>