$函数。它通常返回一个HTML元素或一个HTML元素的集合,通常如下
function $(){
var element = [];
for(var i=0, len=arguments.length; i<len; ++i){
var element = arguments[i];
if(typeof element ==== 'string'){
element = document.getElementById(element);
}
if(arguments.length === 1){
return element;
}
elements.push(element);
}
return elements;
}
稍加改造之后就会变成一个 拥有自身方法,并可以链式调用的小框架了
(function(){
function _$(els){
this.elements = [];
for(var i=0,len=els.length; i<len; ++i){
var element = els[i];
if(typeof element === 'string'){
element = document.getElementById(element);
}
this.elements.push(element)
}
}
_$.prototype = {
each: function(fn){
for(var i=0, len=this.elements.length; i<len; ++i){
fn.call(this, this.elements[i])
}
return this;
},
setStyle: function(prop, val){
this.each(function(el){
el.style[prop] = val;
});
return this;
},
show: function(){
var that = this;
this.each(function(el){
that.setStyle('display', 'block');
});
return this;
}
}
window.$ = function(){
return new _$(arguments);
};
})()
function $(){
var element = [];
for(var i=0, len=arguments.length; i<len; ++i){
var element = arguments[i];
if(typeof element ==== 'string'){
element = document.getElementById(element);
}
if(arguments.length === 1){
return element;
}
elements.push(element);
}
return elements;
}
稍加改造之后就会变成一个 拥有自身方法,并可以链式调用的小框架了
(function(){
function _$(els){
this.elements = [];
for(var i=0,len=els.length; i<len; ++i){
var element = els[i];
if(typeof element === 'string'){
element = document.getElementById(element);
}
this.elements.push(element)
}
}
_$.prototype = {
each: function(fn){
for(var i=0, len=this.elements.length; i<len; ++i){
fn.call(this, this.elements[i])
}
return this;
},
setStyle: function(prop, val){
this.each(function(el){
el.style[prop] = val;
});
return this;
},
show: function(){
var that = this;
this.each(function(el){
that.setStyle('display', 'block');
});
return this;
}
}
window.$ = function(){
return new _$(arguments);
};
})()