Clicking on the anchor displays the alert, but then it tries to take me to the somepage. I thought the preventDefault would prevent this.
<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.
And that stands to reason; in your code, e
is never defined.
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();
}
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.