1.解绑 on关键字绑定的事件
on关键字绑定事件
语法:dom对象.on事件名=事件处理函数通过使用null覆盖事件处理函数实现事件的解绑
语法:dom对象.on事件名=null
代码如下:
<!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>解绑事件</title>
</head>
<body>
<button>按钮</button>
<script>
// 给button按钮注册点击(click)事件
document.querySelector('button').onclick = function() {
alert('点击了')
}
// on关键字 解绑事件
document.querySelector('button').onclick = null
</script>
</body>
</html>
2.解绑 addEventListener 绑定的事件
addEventListener 绑定事件
语法:dom对象.addEventListener('事件',处理函数)使用 removeEventListener()解绑
语法:dom对象.removeEventListener('事件类型', 事件处理函数)注意:匿名函数无法被解绑,所以使用具名函数
代码如下:
<!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>
<button>按钮</button>
<script>
// 注意:匿名函数无法被解绑,所以使用具名函数
function fn() {
alert('点击了')
}
// 给button按钮注册点击(click)事件
document.querySelector('button').addEventListener('click', fn)
// 解绑
document.querySelector('button').removeEventListener('click', fn)
</script>
</body>
</html>