日期:2014-05-16  浏览次数:20454 次

javascript 自定义 id class 选择器实现 支持链式操作
;(function(){
window.Query = window.$ = function(){
var _this = {},selector = arguments[0];
$.prototype = _this;
/**
* 判断是对象是数组还是名值对象
* @param {Object} obj
*/
function objOrArr (obj){
if(!obj)return;
if(typeof obj === "object"){
for(var attr in obj){
return "obj";
}
return obj.push ? "array" : "obj";
}
}
/**
* 确保所有对象都能call
* @param {Object} obj
* @param {Object} callback
*/
function applyAll (obj , callback){
if(!obj)return ;
var idx = 0
if(objOrArr(obj) === "obj"){
for(var i in obj){
if(callback.call(obj[i],i,obj[i]) === false){
break;
}
}
}else{
for(var o = obj[0] ; idx < obj.length && callback.call(o,idx,o) !== false ; o = obj[++idx]){
}
}
}
/**
* id选择器
* @param {Object} selector
*/
function identity (selector){
if(selector){
return document.getElementById(selector);
}
}
/**
* 类选择器
* @param {Object} selector
*/
function clazz (selector) {
var result = [];
if(selector){
var a = selector.split(".");
var prefix = a[0] || "*";
var suffix = a[1];
applyAll(document.getElementsByTagName(prefix),function(){
if(this.nodeType ===1 && this.className){
var classNames = this.className.split(/\s+/g);
var finded = this;
applyAll(classNames,function(){
if(this == suffix){
result.push(finded);
}
});
}else{
}
});
}
return result;
}
/**
*
*/
if(selector){
if(typeof selector === "string"){
if(selector.indexOf(".") != -1)return clazz(selector);
if(selector.indexOf("#")) != -1) return identity(selector);
}
if(typeof selector === "object"){
_this[0] = selector;
return _this[0];
}
if(typeof selector === "function"){
selector(_this);
}
}else{
_this.toString();
}
_this.toString = function(){
return "[Query query]";
}
return _this;
}
})();