js中e.preventDefault()如何使用
在 JavaScript 中,e.preventDefault()
是一个用来禁止事件的默许行动的方法。它通常被用于避免链接的跳转、表单的提交等默许行动。下面是一个简单的例子:
<!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>
在上面的例子中,当用户点击链接时,e.preventDefault()
禁止了链接跳转的默许行动,而是弹出了一个提示框。
TOP