原生JS实现jquery的链式编程。

2023-04-25,,

这是我根据之前遇到的一个面试题,题目:用原生JS实现$("#ct").on("click",fn).attr("id")。

然后看了篇jquery源码分析(http://www.cnblogs.com/aaronjs/p/3279314.html),自己写出来的一个实现,选择器用的querySelector,关于链式编程也只是返回this而已,这也算是自己看jquery源码解决的第一个问题吧,继续加油。

现在想来当年面试官确实没说错,我jquery基础确实差,慢慢学吧,要学的还在很多。

先上代码吧。

 var jq = function(selector){
return new jq.prototype.init(selector);
};
jq.prototype = {
init:function(selector){
this.el = document.querySelector(selector);
return this;
},
on:function(event,fn){
if(window.addEventListener){
this.el.addEventListener(event,fn,false);
}else if(window.attachEvent){
this.el.attachEvent(on+event,fn);
}
return this;
},
attr:function(event,val){
if(!val){
return this.el.getAttribute(event);
}else{
this.el.setAttribute(event,val);
return this;
}
}
}
jq.prototype.init.prototype = jq.prototype; console.log(jq("#ct").on("click",function(){alert("您点击了我。")}).attr("title","我的图片"));

原生JS实现jquery的链式编程。的相关教程结束。

《原生JS实现jquery的链式编程。.doc》

下载本文的Word格式文档,以方便收藏与打印。