[英]Why doesn't the click on the anchor tag first visit the link?
對於以下代碼:
links.addEventListener("click", e => { const a = e.target.closest("a"); if (!a) return; const confirmation = confirm(`Go to ${a.href}?`); if (!confirmation) e.preventDefault(); });
<div id="links"> <p>Lorem ipsum dolor sit <a href="https://wikipedia.org">Wikipedia</a> consectetur adipisicing elit. Molestias temporibus <a href="https://developer.mozilla.org/en-US/"><i>Mozilla Developer Network (MDN)</i></a> labore eveniet dolor sunt soluta voluptate quas. Reprehenderit, quam voluptatem.</p> </div>
為什么單擊a
標簽時不首先訪問鏈接,而只是打開我的 javascript 文件中定義的confirm
?
您需要修改您的JS代碼,首先阻止鏈接的默認行為然后要求確認,如果結果為真,您可以使用window.location
,有一個類似的問題可以為您提供更多信息: 通過添加點擊事件addEventListener 從超鏈接確認導航
您a
標簽沒有轉到href
的原因是 eventListener 獲得優先級。 試試這個代碼:
links.addEventListener("click", e => {
const a = e.target.closest("a");
a.preventDefault()
if (!a) return;
const confirmation = confirm(`Go to ${a.href}?`);
if (confirmation){
window.location.assign(a.href);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.