JS模拟jquery事件监听
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="btn1" onclick="console.log(111)">on</button>
<button id="btn2">off</button>
<script type="text/javascript">
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
//事件绑定
Element.prototype.on = function(type, fn) {
if(window.addEventListener) { //高级浏览器事件绑定
this.addEventListener(type, fn,false);
} else { //IE9以下浏览器
this.attachEvent('on' + type, fn);
}
}
//解除事件绑定
Element.prototype.off = function(type, fn) {
if(window.removeEventListener) { //高级浏览器事件绑定
this.removeEventListener(type, fn, false);
} else { //IE9以下浏览器
this.detachEvent('on' + type, fn);
}
}
btn1.on('click', function() {
console.log("触发点击事件");
});
btn2.on('click', function() {
btn1.off('click', function() {
console.log("解除事件绑定");
});
});
</script>
</body>
</html>