[英]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);
How can I prevent the link action to go to example.com?如何防止链接操作转到example.com?
Event handlers that are registered with .addEventListener()
(the modern, standard way to register events), are automatically passed a reference to the event
object that represents the event that triggered the handler in the first place.使用.addEventListener()
(注册事件的现代标准方式.addEventListener()
注册的事件处理程序会自动传递对event
对象的引用,该对象代表首先触发处理程序的事件。 This event
object has many properties, but the following two are what you are looking for:这个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.