JQuery模块分析及其实现第五部分事件部分功能及实现,接第四部分!
dom
元素删除掉this
上的所有 dom
元素;dom
元素的父节点,调用 removeChild
方法删除自己;this
.remove: function() {
return this.each(function() {
this.parentNode.removeChild(this);
});
},
dom
元素,清空后代节点this
上的所有 dom
元素;dom
元素的 innerHTML
属性赋值为空字符串;this
,实现链式编程.empty: function() {
return this.each(function() {
this.innerHTML = '';
});
}
以上接第四部分 dom
操作模块
事件部分begin
dom
元素的 on + 事件名
属性来绑定事件,并且赋值为 一个字符串;dom
元素的 on + 事件名
属性来绑定事件,并且赋值为 一个事件处理函数;js
代码和 html
的耦合度关系;attachEvent
来绑定事件;dom.attachEvent(type, callback)
;detachEvent(type, callback)
;addEventListener
方法来给dom元素绑定事件;dom.addEventListener(type, callback, useCapture默认值为false)
;removEventListener(type, callback)
;IE
标准需要加 on
前缀W3C
标准不加 on
前缀IE
在执行事件处理函数时,顺序不定(根据版本),而 W3C
按照对垒结构来一次执行事件的处理函数this
指向不同window
dom
元素W3C
标准,使用 addEventListener
来绑定事件attachEvent
来绑定事件//提前返回
var addEvent = function() {
// 如果符合W3C标准,使用addEvnetListener绑定事件
if (global.addEventListener) {
return function(elem, type, callback, useCapture) {
elem.addEventListener(type, callback, useCapture || false);
};
} else { // 否则就使用IE标准的 attachEvent绑定事件
return function(elem, type, callback) {
elem.attachEvent('on' + type, callback);
};
}
}();
W3C
标准,使用 removeEventListener
来移除事件处理函数detachEvent
来移除事件处理函数//提前返回
var removeEvent = function() {
if (global.removeEventListener) {
return function(elem, type, callback) {
elem.removeEventListener(type, callback);
};
} else {
return function(elem, type, callback) {
elem.detachEvent('on' + type, callback);
};
}
}();
itcast
对象上的所有的 dom
元素绑定事件this
上所有 dom
元素addEvent
给当前遍历到的 dom
元素绑定事件this
,实现链式编程on: function(type, callback, capture) {
return this.each(function() {
addEvent(this, type, callback, capture);
});
},
itcast
对象上所有 dom
元素的事件处理函数this
上所有 dom
元素removeEvent
给当前遍历到的 dom
元素移除相应事件的处理函数this
,实现链式编程off: function(type, callback) {
return this.each(function() {
removeEvent(this, type, callback);
});
}
itcast
对象上的所有的 dom
元素绑定单击事件处理函数的itcast对象.click(callback)
;this
上的所有 dom
元素addEventListener
分别传值即可return this
实现链式编程click: function(callback, capture) {
return this.each(function() {
addEvent(this, 'click', callback, capture);
});
}
itcast.each(['click', 'dblclick', 'keypress', 'keyup', 'keydown', 'mouseover', 'mouseout',
'mouseenter', 'mouseleave', 'mousemove', 'mouseup', 'mousedown'], function(type) {
itcast.fn[type] = function(callback, capture) {
return this.on(type, callback, capture);
};
});
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有