事件绑定和移除
事件:是用户与页面交互的桥梁,页面通过事件告诉用户做了哪些操作
事件的绑定方式
1 如果事件函数代码量少,可以直接写标签的onlick属性上面
<button οnclick="var con='hello';alert(con)">点我1</button>
2 绑定方式 添加onclick属性=函数调用格式
<button οnclick="f1()">点我</button>
3 绑定方式 通过js添加onclick属性进行绑定
<button id="b3">点我3</button>
4 绑定方式
<button id="b4">点我4</button>
function f1(){
console.log(this,"++++")//window
console.log(event)//事件对象
//event.target 代表的是按钮元素对象
event.target.style.backgroundColor="red"
}
//DOM0事件:通过添加onclick属性进行绑定事件的方式,只能绑定一个方法。
var btn3=document.querySelector("#b3")
btn3.οnclick=function(){
console.log*(this,"++++")//buttton对象
console.log(event)
this.style.backgroundColor="yellow"
}
btn3.οnclick=function(){
console.log("ddd");
}
//把事件移除的方式 dom移除方式 把onclick属性=""或者null
//btn3.οnclick=''
//btn3.οnclick=null
//DOM2事件 可以绑定多个事件函数,并且可以通过true/false设置在捕捉或者冒泡过程触发函数
var btn4=document.querySelector("#b4")
//addEventListener() 添加事件监听
//参数1 事件名,不带on的
//参数2 事件函数
//参数3 true/false
function ff(){
console.log("ff")
}
function fff(){
console.log("fff")
}
btn4.addEventListener("click",ff,false)
btn4.addEventListener("click",fff,false)
//移除事件函数
btn4.removeEventListener("click",fff)