用途:适合无线下拉图片列表每个图片的事件监听
function bindEvent(elem, type, selector, fn) {
// 如果传了三个参数,则第三个参数就是fn
if(fn == null){
fn = selector
selector = null
}
elem.addEventListener(type, event => {
const target = event.target
if (selector) {
// 代理绑定,绑定无限个
if (target.matches(selector)) {
fn.call(target, event)
}
} else {
// 普通绑定
fn.call(target, event)
}
})
}
const test1 = document.getElementById("tyre")
const event1 = function () {
console.log(this.innerText);
}
// 绑定多个
bindEvent(test1,'click','p',event1)
// 绑定一个
const event2 = function () {
console.log(this.id);
}
bindEvent(test1,'click',event2)
<div id="tyre">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>
<p>6</p>
<p>7</p>
<p>8</p>
<p>9</p>
</div>
函数bindEvent传入四个参数(父节点,需要绑定的事件类型,需要绑定的节点,事件内容)