常见绑定事件和几个常见的 this
方式1 :this 代表 object window
<div style="width: 100px;height: 80px;background: red" onclick="add()">1</div>
<script type="text/javascript">
function add(){
alert(this) //这里的 this 代表全局变量 window
}
</script>
方式2:this 代表选择的标签
<div style="width: 100px;height: 80px;background: red" onclick="add(this)">1</div>
<script>
function add(self){
alert(self)
// 这里的self 代表选择的标签
}
</script>
绑定事件
<div id="i1" style="width: 100px;height: 80px;background: red" >1</div>
<script>
tag =document.getElementById('i1')
tag.onclick = function(){
alert(this)
this.style.background='yellow'
}
// this 代表选择的标签
</script>
绑定多个事件:addEventListener
addEventListener('事件',函数,false或true)
布尔值,指定事件是否在捕获或冒泡阶段执行。
false :代码在上面的先出来,事件句柄在捕获阶段执行
true:代码在下面的先出来,默认。事件句柄在冒泡阶段执行
浏览器支持:IE8 及更早IE版本不支持 addEventListener() 方法,,Opera 7.0 及 Opera 更早版本也不支持。 但是,对于这些不支持该函数的浏览器,你可以使用 attachEvent() 方法来添加事件句柄
removeEventListener()
移除 事件 , 浏览器支持同上 detachEvent()
<div id="a" style="background: red; width: 400px; height: 300px;">1</div>
<script type="text/javascript">
var tag =document.getElementById('a')
tag.addEventListener('click',function(){console.log('aaa')},false)
tag.addEventListener('click',function(){console.log('bbb')},false)
</script>