JavaScript e.preventDefault() Guide

In JavaScript, e.preventDefault() is a method used to prevent the default behavior of an event. It is commonly used to stop the default actions such as preventing links from redirecting or forms from submitting. Here is a simple example:

<!DOCTYPE html>
<html>
<head>
  <title>Prevent Default Example</title>
</head>
<body>

<a href="https://www.example.com" id="link">Click me</a>

<script>
document.getElementById('link').addEventListener('click', function(e) {
  e.preventDefault(); // 阻止链接的默认行为
  alert('You clicked on the link!');
});
</script>

</body>
</html>

In the example above, when the user clicks on the link, e.preventDefault() prevents the default behavior of the link jumping, instead popping up an alert box.

bannerAds