[英]Why doesn't the click on the anchor tag first visit the link?
For the following code:对于以下代码:
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>
Why doesn't a click on the a
tag first visit the link but just opens the confirm
which is defined in my javascript file?为什么单击a
标签时不首先访问链接,而只是打开我的 javascript 文件中定义的confirm
?
您需要修改您的JS代码,首先阻止链接的默认行为然后要求确认,如果结果为真,您可以使用window.location
,有一个类似的问题可以为您提供更多信息: 通过添加点击事件addEventListener 从超链接确认导航
The reason your a
tag does not go to the href
is because the eventListener gets priority.您a
标签没有转到href
的原因是 eventListener 获得优先级。 Try this code instead:试试这个代码:
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.