JSFiddle - React, Tailwind, and code Playground
by rubys
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js 多个事件的绑定及移除</title>
</head>
<body>
<button id="button">button</button>
<button id="unbind">unbind</button>
<script>
window.onload = function() {
var button = document.querySelector('#button');
var unbind = document.querySelector('#unbind');
// 1、使用匿名函数添加事件
// 这种绑定没有办法移除, 除非移除全部 click 事件
button.addEventListener('click', function(e) {
console.log('click');
});
// 2、使用命名函数添加事件
// 这种绑定方法可以通过函数引用作为参数移除
button.addEventListener('click', click1);
unbind.addEventListener('click', function(e) {
console.warn('unbind click1');
button.removeEventListener('click', click1);
});
};
function click1(e) {
console.log('click1')
}
</script>
</body>
</html>