简体   繁体   中英

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?

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. This event object has many properties, but the following two are what you are looking for:

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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