[英]preventDefault does not seem to work
Clicking on the anchor displays the alert, but then it tries to take me to the somepage.单击锚点会显示警报,但随后它会尝试将我带到某个页面。 I thought the preventDefault would prevent this.
我认为 preventDefault 会阻止这种情况。
<body>
<a id="someLink" href="somepage.html">Click Me</a>
<script>
var link = document.getElementById("someLink");
function linkClick () {
alert("this goes nowhere");
e.preventDefault();
}
link.addEventListener("click", linkClick);
</script>
</body>
Always check the console.始终检查控制台。
You'll see an error telling you e is not defined.你会看到一个错误,告诉你 e 没有定义。
And that stands to reason;这是有道理的; in your code,
e
is never defined.在您的代码中,从未定义过
e
。
You've probably referenced this from other code you've seen.您可能已经从您看过的其他代码中引用了它。 What you've not done is provided a container for the event object to be passed, as the first parameter, to your event callback.
您还没有做的是为要传递给事件回调的事件对象(作为第一个参数)提供了一个容器。
function linkClick (e) { //<-- now we can talk to @e
alert("this goes nowhere");
e.preventDefault();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.