.contains(target)) {
matchTarget = target;
break;
}
}
matchTarget && func.call(matchTarget, ev);
}
bindEvent(el, type, agent);
}
ok,一个简易的事件委托的框架大体完成了,接下来就是要合并一下,合并成我们常用的。
Element.prototype._on = function(type, selector, func){
if (selector && func == undefined) {
func = selector;
selector = null;
bindEvent(this, type, func);
console.log('on');
}else if (selector == undefined && func == undefined) {
bindEvent(this, type, function(ev){ev.preventDetault()})
console.log('null');
} else{
delegateEvent.apply(this, arguments)
console.log('delegate');
}
}
该_on方法,接受3个参数:type(事件类型), selector(指定触发事件的元素), func(触发的事件)。
使用方法如document.body._on('click', 'a', function(){console.log(this)}),给body绑定一个点击事件,当点击a标签后,打印出该标签在控制台上。
结语最近已经越来越少写jq的,网站交互少是一个方面,使用了angular也是另一个方面。
完整的代码:
(function(window,undefined){
function bindEvent(el, type, func){
if (el.addEventListener) {
el.addEventListener(type, func, false);
}else if (el.attachEvent) {
el.attachEvent(type, func);
}else{
el['on'+type] = func;
}
}
function delegateEvent(type, selector, func){
var agent = function(ev){
var target = ev.target || ev.srcElement;
var targets = this.querySelectorAll(selector);
// console.log(targets);
var matchTarget = null;
for (var i = 0; i < targets.length; i++) {
if (target === targets || targets.contains(target)) {
matchTarget = target;
break;
}
}
matchTarget && func.call(matchTarget, ev);
}
bindEvent(this, type, agent);
}
Element.prototype._on = function(type, selector, func){
if (selector && func == undefined) {
func = selector;
selector = null;
bindEvent(this, type, func);
console.log('on');
}else if (selector == undefined && func == undefined) {
bindEvent(this, type, function(ev){ev.preventDetault()})
console.log('null');
} else{
delegateEvent.apply(this, arguments)
console.log('delegate');
}
}
})(window);
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |