【问题标题】:prevent default link action with addeventlistener使用 addeventlistener 阻止默认链接操作
【发布时间】:2021-04-12 03:21:19
【问题描述】:
<a id="link" href="example.com">test</a>

var a = document.getElementById(link);
a.addEventListener('click',function(e){
//code
}, false);

如何防止链接操作转到 example.com?

【问题讨论】:

  • Prevent anchor behaviour的可能重复
  • return false 对事件监听器不起作用
  • @machiine 该线程中还建议了其他选项。

标签: javascript


【解决方案1】:

使用.addEventListener()(注册事件的现代标准方法)注册的事件处理程序会自动传递对event 对象的引用,该对象表示首先触发处理程序的事件。这个event 对象有很多属性,但以下两个是您要查找的:

document.getElementById("link").addEventListener('click',function(e){
   e.preventDefault(); // Cancel the native event
   e.stopPropagation();// Don't bubble/capture the event any further
});
&lt;a id="link" href="example.com"&gt;test&lt;/a&gt;

【讨论】:

  • 应该是"link"
猜你喜欢
  • 2019-04-09
  • 2012-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多