样式代码
<style>
div {
width: 200px;
height: 200px;
background-color: pink;
}
</style>
body代码
<div></div>
0. 获取元素
var box = document.querySelector('div')
1. 给 box 元素添加一个点击事件
box.onclick = function () {
console.log('点击事件 1, 触发了~~~')
}
2. 给 box 元素添加第二个点击事件
box.onclick = function () {
console.log('点击事件 2, 触发了~~~')
}
问题:
我们现在注册事件就是通过 onXXX
只能给元素注册一个事件, 如果写了第二个, 那么第一个就会被覆盖掉
解决:
如果想要两个事件全都存在, 我们可以使用 事件监听的方式去给元素绑定事件
使用
addEventListener 去给元素通过事件监听的方式
在 IE 中需要使用 attachEvent (了解即可)