【发布时间】: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");
});
现在我有一个问题,如果我点击<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