繁体   English   中英

使用 addeventlistener 阻止默认链接操作

[英]prevent default link action with addeventlistener

<a id="link" href="example.com">test</a>

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

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

使用.addEventListener() (注册事件的现代标准方式.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 });
 <a id="link" href="example.com">test</a>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM