手写事件代理(兼容IE浏览器)
程序员文章站
2023-12-30 21:04:04
...
<div id="btns">
<button data-id="1">按钮1</button>
<button data-id="2">按钮2</button>
<button data-id="3">按钮3</button>
<button data-id="4">按钮4</button>
<div>666</div>
</div>
function bindEvent(obj, type, fn) {
if (obj.addEventListener) {
obj.addEventListener(type, eventFn);
} else {
obj.attachEvent("on" + type, eventFn);
}
function eventFn(e) {
var e = e || window.event;
var target = e.target || e.srcElement;
fn && fn.call(target,e)
}
}
bindEvent(document.getElementById('btns'),'click',function(e){console.log(e.target.innerHTML,e.target.dataset.id)})