JS实现jQuery的attr()、on()方法
这里用原生JS实现的attr()、on()方法,与jQuery里的attr()、on()方法一样能够进行链式调用。
回顾jQuery中的attr()与on()方法
- attr()
设置或返回相应元素的属性值,与原生JS中的setAttribute()方法相似 - on()
在被选元素上添加事件及其事件行为(此方法在jQuery1.7后逐渐代替bind()、live() 和 delegate() 方法)
原生JS实现attr()方法
利用setAttribute()方法实现:
Object.prototype.attr = function(attr, value) {
if(value === undefined) {
this.getAttribute(attr);
return this;
} else {
this.setAttribute(attr, value);
return this;
}
};
原生JS实现on()方法
//由于jQuery2.0以上版本对IE8及其以下浏览器已经无效,因此在引用jQuery包的时候需要引用jQuery1.x版本
Object.prototype.on = function(event, callback) {
if(window.addEventListener){
this.addEventListener("event", function() {
callback();
}, false);
return this;
}else if(window.attachEvent){
//attachEvent函数的this指向window,addEventListener的this指向调用对象
//由于if下的{}不会形成墙,把正确的this通过bind()注射进来从而改变回调函数里面指向window的this
this.attachEvent('on'+event,function(){
callback();
}.bind(this));
return this;
}
}
问题:请使用原生JS实现jQuery中的attr()、on()方法
知识点:setAttribute()、getAttribute()、attr()、on()方法的原理