1、event.preventDefault(); // 阻止默认行为,例如阻止 a 链接默认的跳转行为,阻止表单提交
阻止a链接的默认跳转行为 阻止表单提交
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="http://www.baidu.com" id="link">点击跳转</a>
<br>
<form action="1.php">
<input type="text" />
<button class="btn">点击提交</button>
</form>
<script>
// 获取元素a链接
const link=document.querySelector('#link')
console.log(link);
// 给a绑定点击事件
link.addEventListener('click',function jump(e){
console.log(e);
e.preventDefault()
})
// 获取按钮
const btn=document.querySelector('.btn')
// 给按钮绑定点击事件
btn.addEventListener('click',function submit(e){
console.log(e);
e.preventDefault()
})
</script>
</body>
</html>
2、event.stopPropagation(); // 阻止冒泡
3、event.stopImmediatePropagation(); // 按钮绑定了 2 个响应函数,依次注册 a,b 两个事件,点击按钮,a 事件中加 event.stopImmediatePropagation()就能阻止 b 事件
4、event.currentTarget // 早期的 ie 不支持,当前绑定的事件
5、event.target