欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

原生jQuery代码

程序员文章站 2022-05-18 23:10:58
function myJquery(selector){ if(typeof selector=="string") { if (selector.charAt(0) == "<" && selector.slice(-1) == ">") { var ele = selector.slice(1, ......
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);
}