实例
注册事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button>传统注册事件</button>
<button>方法监听注册事件</button>
</body>
<script>
var btns = document.querySelectorAll('button')
// btns[0].οnclick=function (){
// alert('你好')
// }
// btns[0].οnclick=function (){
// alert('哈喽')
// }
btns[1].addEventListener("click", function (){
alert('再见')
})
btns[1].addEventListener('click', function (){
alert('再也不见')
})
</script>
</html>
传统注册事件(会覆盖)
方法监听注册事件(不会覆盖)
删除事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
div{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<div>1</div>
<div>2</div>
<div>3</div>
<script>
var divs = document.querySelectorAll('div')
divs[0].onclick = function () {
alert('哈哈')
// 传统删除事件的方式
this.onclick = null;
}
divs[1].addEventListener('click', fn) // 传函数名,不是调用
function fn() {
alert('haha')
this.removeEventListener('click', fn)
}
</script>
</body>
</html>
传统删除事件
方法监听删除事件
事件流
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.father {
overflow: hidden;
width: 300px;
height: 300px;
margin: 100px auto;
background-color: pink;
text-align: center;
}
.son {
width: 200px;
height: 200px;
margin: 50px;
background-color: blue;
line-height: 200px;
color: #fff;
}
</style>
</head>
<body>
<div class="father">
<div class="son">son盒子</div>
</div>
<script>
// dom 事件流三个阶段
// 1. js只能执行捕获或者冒泡其中的一个
// 2、 onclick 只有冒泡
// addEventListener(type, func, bool)
// 第三个参数 是true 处于捕获阶段
// document -> html -> body -> father -> son
// var son = document.querySelector('.son')
// son.addEventListener('click', function () {
// alert('son')
// }, true)
// var father = document.querySelector('.father')
// father.addEventListener('click', function () {
// alert('father')
// }, true)
//
// document.addEventListener('click', function () {
// alert('document')
// },true)
//
// 冒泡阶段 第三个参数 是false或者不写 处于冒泡阶段
// son -> father -> body -> html -> document
var son = document.querySelector('.son')
son.addEventListener('click', function () {
alert('son')
}, false)
var father = document.querySelector('.father')
father.addEventListener('click', function () {
alert('father')
}, false)
document.addEventListener('click', function () {
alert('document')
},false)
</script>
</body>
</html>