function fDelegate(parentSelector,targetSelector,event,callback){ var parent = document.querySelector(parentSelector); parent.addEventListener(event,fEventHandler,false); function fEventHandler(e){ var target = e.target, //currentTarget = e.currentTarget;//parent代替 while(target != parent){ if(target.matches(targetSelector)){ callback.apply(target,Array.prototype.slice.call(arguments)); break; } target = target.parentNode; } } } if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; }
调用:
fDelegate('#list', 'li', 'click', function () { console.log(this); });
事件委托优点:
1.减少内存消耗,不必为大量元素绑定事件
2.为动态添加的元素绑定事件
事件委托的缺点:
1.部分事件如 focus、blur 等无冒泡机制,所以无法委托。
2.事件委托有对子元素的查找过程,委托层级过深,可能会有性能问题
3.频繁触发的事件如 mousemove、mouseout、mouseover等,不适合事件委托