簡體   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