您的位置:首页 > Web前端 > JQuery

简单模仿jquery的几个特性

2014-10-18 15:30 387 查看
使用了jquery之后,原生的javascript写的很少了,最近准备复习下,于是想到了自己写一点js来模拟jquery的几个核心特性。

先看页面代码:

function JQuery(selector){

this.selector=selector;
this.domEles=[];

//get domEles
if(this.selector.indexOf("#")==0){                //id selector
var id=this.selector.replace("#","");
var ele=document.getElementById(id);
this.domEles.push(ele);
}else if(this.selector.indexOf(".")==0){        //class selector
var cls=this.selector.replace(".","");
var eles=document.getElementsByClassName(cls);
for(var i=0;i<eles.length;i++){
this.domEles.push(eles[i]);
}
}

this.click=function(func){
if (func) {
for(var i = 0;i<this.domEles.length;i++){
this.domEles[i].onclick=func;
}
}
return this;
}

this.text=function(txt){
if(txt){
for(var i=0;i<this.domEles.length;i++){
this.domEles[i].innerText=txt;
}
return this;
}else{
//jquery中好像是返回的多个元素的文本内容,这里只返回第一个匹配元素的文本内容
if(this.domEles.length>0)
return this.domEles[0].innerText;
}
}

this.html=function(html){
if(html){
for(var i=0;i<this.domEles.length;i++){
this.domEles[i].innerHTML=html;
}
return this;
}else{
if(this.domEles.length>0)
return this.domEles[0].innerHTML;
}
}

this.addClass=function(className){
if(!className||className.length<1) throw "className";

for(var i=0;i<this.domEles.length;i++){
var strCls=this.domEles[i].attributes["class"].value;
var classNames=strCls.split(" ");
var objCls=[];
for(var j=0;j<classNames.length;j++){
if(classNames[j]==""||classNames[j]==className)continue;

objCls.push(classNames[j]);
}
objCls.push(className);
this.domEles[i].attributes["class"].value=objCls.join(" ");
}

return this;
}
}

function $(){

if (arguments.length<1) {throw "$函数缺少参数!"};

if(typeof(arguments[0])=="function"){
window.onload=arguments[0];
}else if(typeof(arguments[0])=="string"){
//这里不考虑创建元素的情况
return new JQuery(arguments[0]);
}
}

/*

1.参数重载一般是通过参数类型(typeof)和长度(arguments.length)的判断;
2.浏览器兼容问题一般是通过方法可用性检查;

*/


View Code
做了什么:

1.注册文档加载完成的事件处理程序;

  $()函数中判断参数是否是一个函数,如果是就将该函数注册给window.onload时间。
2.id、class选择器;

  利用document.getElementById和document.getElementByClassName函数实现。
3.click事件绑定函数;

  分别给匹配的每一个dom元素绑定onclick事件。
4.text函数获取元素文本;

  获取第一个(或设置所有)匹配元素的innerText属性。
5.html函数设置元素html内容;

  获取或设置所有匹配元素的innerHTML属性。
6.addClass函数为元素添加css class;

  向所有匹配元素中添加一个class。
7.链式操作;

  jquery对象的方法最后返回this,函数式编程:$("").html("").addClass("")。
8.隐式迭代

  默认的将操作作用在匹配的所有元素上,关键在于jquery对象中有一个存储dom对象的数组:domELes。

说明:jquery的强大真的可以让我们写很少的代码来实现需要的效果,但不要用了jquery忘了javascript。

当然这里的简单实现目的只是为了展示jquery的几个特性的大致实现原理,代码当中也有很多不妥之处,这里也没有模拟jquery的dom操作、动画、浏览器兼容、Ajax等重要特性。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: