1. 在HTML中绑定
<input id="btn" type="button" onclick="btnFunc()">
2.在JavaScript中绑定
-
onType
//html
<button id="btn">点击按钮</button>
//js
var d = document.getElementById('btn');
d.onclick = function() {
console.log('我被点击了,onclick') //输出:我被点击了,onclick
}
优点:兼容性好
缺点:过于古老,只能绑定一个函数,等同于写在DOM上的attribute
-
addEventListener('TYPE,function,Boolean)
第一个参数:是要注册处理程序的事件类型
第二个参数:当指定类型的事件发生时应该调用的函数
第三个参数:是个布尔值,通常情况下传false。如果传了true,那么函数将注册为捕获事件处理程序,并在事件不同的调度阶段调用
addEventListener 中的this是当前绑定事件的对象
//html
<button id="btn">点击按钮</button>
//js
var d = document.getElementById('btn');
d.addEventListener('click', function() {
console.log("我被点击了,click")
})
优点:可以绑定多个函数,同一函数只能绑定一次
缺点:IE9以下不支持
-
attachEvent(TYPE,function)
TYPE,Function意义同addEventListener() 没boolean值是因为IE事件模型不支持捕获
IE5定义的,我用最新版IE发现报错,
attachEvent中的this是window
//html
<button id="btn">点击按钮</button>
//js
var d = document.getElementById('btn');
d.attachEvent('onclick',function() {
console.log("我被点击了") // 对象不支持“attachEvent”属性或方法
})
优点:可以绑定多个函数,同一函数可以绑定多次
缺点:只能在IE中使用,现在的高版本会报错
写个适配的点击事件
- 函数的方式
//html
<button id="btn">点击按钮</button>
//js
var d = document.getElementById('btn');
function addEvent(elmt, type, func) {
if(elmt.addEventListener) {
elmt.addEventListener(type, func, false)
}else if(elmt.attachEvent) {
elmt.attachEvent('on' + type, function(){
func.call(elmt)
})
}else {
elmt['on' + type] = func
}
}
function divclick() {
console.log('我又被点击了,qaq') //打印:我又被点击了,qaq
}
addEvent(d, 'click', divclick)
- element.prototype
//html
<button id="btn">点击按钮</button>
//js
var d = document.getElementById('btn');
Element.prototype.addEvent = function(type, func) {
let elmt = this
if(elmt.addEventListener) {
elmt.addEventListener(type, func, false)
}else if(elmt.attachEvent) {
elmt.attachEvent('on' + type, function(){
func.call(elmt)
})
}else {
elmt['on' + type] = func
}
}
function divclick() {
console.log(this) //打印:<button id="btn">点击按钮</button>
console.log('天哪,还点击我') //打印:天哪,还点击我
}
d.addEvent('click', divclick)
解绑定
- onType = null
- eventTarget.removeEventListener(TYPE, function)
-
element.datachEvent(onType, function)
兼容性问题和绑定事件一样