我如何防止嵌套在另一个也使用 onclick 的元素上的链接上的单击事件



我有这个简单的代码

<span class="doit"><a class="doit"href="ww.domain.com">text</a></span>

我希望点击类"do it"触发一个函数,所以我尝试了这个

$(document).on('click', '.doit', function(e) {
    // prevents to handle the click for nested objects again
    e.stopPropagation();
    alert("hello world"); 
});

现在我遇到了一个问题,如果我单击<a href,来自 href 的链接将打开,而不是 on.click 函数将被触发。

如何防止链接被触发而不是 on.click 事件?

更新 1

我尝试了一个建议的答案,失败了,因为 href 链接已经打开。我必须准备打开链接,只有 on.click 事件应该有效。

<span class="doit">
 <a class="doit" href="http://www.example.com" target="_blank">webcms von 
  <span class="doit">ABC</span>
  <span class="doit">123</span>
 </a>
</span>
if ($(e.target).is("a")) {     
    e.preventDefault(); // stop the href 
    alert("I WILLL not go to " + e.target.href);
    e.cancelBubble = true; // do not click through
    e.stopPropagation(); // just stop the event or it will trigger again on the span
    return false; 
}
console.log('target:'+e.target);

在控制台中,我读到:[对象 HTMLSpanElement

我必须找到一种方法,它以各种方式对 html 标签进行排序或嵌套。

更新 2

if ($(e.target).is("a")) 
{     
      e.preventDefault(); // stop the href  
}
e.cancelBubble=true; // do not click through
e.stopPropagation(); // just stop the event or it will trigger again on the span
alert("hello world");

我看到警报"hello world",但之后,链接仍将打开

只需测试

但是,我不建议您对这两个元素进行相同的类

在这里,您可以单击链接和跨度触发器的单击,但不能单击 href

顺便说一下,嵌套范围不是正确的 HTML

$(document).on('click', '.doit', function(e) {
  if ($(e.target).is("a")) {
    e.preventDefault(); // stop the href 
    alert("I WILLL not go to " + e.target.href);
  }
  e.cancelBubble=true; // do not click through
  e.stopPropagation(); // just stop the event or it will trigger again on the span
  alert("hello world");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="doit">
 <a class="doit" href="http://www.example.com" target="_blank">webcms von 
  <span class="doit">4U</span>
  <span class="doit">.tools</span>
 </a>
</span>

另类

$(document)
  .on('click', 'a.doit', function(e) {
    e.preventDefault();
    alert("I WILLL not go to " + e.target.href);
  })
  .on('click', 'span.doit', function(e) {
    alert("hello world");
    e.cancelBubble=true;  e.stopPropagation()
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="doit">
 <a class="doit" href="http://www.example.com" target="_blank">webcms von 
  <span class="doit">4U</span>
<span class="doit">.tools</span>
</a>
</span>

最新更新