原生jQuery代码

时间:2019-03-13
本文章向大家介绍原生jQuery代码,主要包括原生jQuery代码使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
function myJquery(selector){
if(typeof selector=="string") {
if (selector.charAt(0) == "<" && selector.slice(-1) == ">") {
var ele = selector.slice(1,-1);
this[0] = document.createElement(ele);
this.length = 1;
} else {
var all=document.querySelectorAll(selector);
for (var i = 0; i < all.length; i++) {
this[i] = all[i];
}
this.length = all.length;
}
}else if(typeof selector=="undefined"){
return this;
}else if(typeof selector=="function"){
this.ready(selector);
}else if(selector.nodeType==1){
this[0]=selector;
this.length=1;
}
}

myJquery.prototype={
each:function(callback){
for (var i=0;i<this.length;i++){
callback(i,this[i]);
}
},
html:function(val){
this.each(function(index,obj){
obj.innerHTML=val
});
return this;
},
css:function(attr,val){
this.each(function(index,obj){
if (typeof attr=="object"){
for (var i in attr){
if (i=="width"||i=="height"||i=="margin"||i=="fontSize"){
obj.style[i]=parseInt(attr[i])+"px";
}
obj.style[i]=attr[i];
}
}else{
obj.style[attr]=val;
}
})
return this;
},
ready:function(callback){
document.addEventListener("DOMContentLoaded",function(){
callback();
})
},
click:function(callback){
this.each(function(index,obj){
obj.onclick=function(){
callback.call(obj);
}
})
return this;
},
appendTo:function(dom){
if (typeof dom=="string"){
var all=document.querySelectorAll(dom)
var ele=this[0]
for (var i=0;i<all.length;i++){
this[i]=ele.cloneNode(true)
all[i].appendChild(this[i])
this.length=all.length
}
}else{
dom.appendChild(this[0])
}
// document.querySelector(dom).appendChild(this[0]);
return this;
}

}
function $(selector){
return new myJquery(selector);
}