是同时能用于普通和代理绑定的事件绑定函数,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<a href="#">链接1</a>
<a href="#">链接2</a>
<a href="#">链接3</a>
<button>加载更多。。。</button>
</body>
<script>
function bindEvent(elem, type, selector, fn) {
if (fn == null) { //等于null或者undefined
fn = selector
selector = null
}
elem.addEventListener(type, event => { //event由addEventListener传入,包含了触发事件对象的相关信息
const target = event.target
if (selector) {
// 代理绑定
if (target.matches(selector)) {
fn.call(target, event)
}
} else {
//普通绑定
fn.call(target, event) //这里是执行fn
}
})
}
const btn = document.getElementsByTagName('button')[0]
bindEvent(btn, 'click', function (event) { //这里是执行bindEvent,定义fn
console.log(event)
event.preventDefault()
alert(this.innerHTML)
})
//代理绑定
const body = document.getElementsByTagName('body')[0]
bindEvent(body, 'click', 'a', function (event) {
event.preventDefault()
alert(this.innerHTML)
})
</script>
</html>
执行效果:http://cdn.tangmingkang.top/H9W%5B%7DRB0D%7BEXC4%5B62TMH%25S6.png