【问题标题】:How I can prevent the click event on a link which is nested on another element which also use onclick?如何防止嵌套在另一个也使用 onclick 的元素上的链接上的单击事件?
【发布时间】:2019-02-01 12:34:45
【问题描述】:

我有这个简单的代码

<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"); 
});

现在我有一个问题,如果我点击&lt;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);

在控制台中我读到:[object HTMLSpanElement

我必须找到一种方法,它适用于 html-tags 的所有排序或嵌套方式。

更新 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”,但在那之后,链接仍然会打开

【问题讨论】:

标签: javascript jquery event-handling event-listener dom-events


【解决方案1】:

只是测试

但是我不建议你给这两个元素赋予相同的类

这里可以点击链接和span的onclick触发,但不能点击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>

【讨论】:

猜你喜欢
相关资源
最近更新 更多
热门标签