今天写了一个很简单、很粗暴的通过js根据类来查找dom元素。
为了降低它的粗暴等级(耗费性能)我给了三个等级。
首先性能最好的,适合ff,ch,ie8,通过queryselectorall这个api。
其次是指定id
最后只能全页面进行匹配class,不过比较节省的性能的是,在指定class名称的时候,同时传入html标签的类型,用于节省遍历的范围!
因为水平有限,目前也只能写成这种,真的好好奇jq的选择器是怎么去匹配dom的,如果有大神看到这篇文章,请不要吝啬施教。。。
下面贴代码:
function $(d,t){
var c = null, // classname
e = null, // element
i = null; // id
function type(p){
/function.(\w*)\(\)/.test(p.constructor);
return regexp.$1.tolowercase();
}
if(type(d) == 'string'){
if(/^\.[a-z,a-z,_]\w*$/.test(d)){ // 匹配class
c = d;
}else if(/^#[a-z,a-z,_]\w*$/.test(d)){ // 匹配id
i = d;
}else if(/^[a-z,a-z,_]+$/.test(d)){ // 匹配元素
e = d;
}else{
return undefined;
}
if(document.queryselectorall){
if(c || e) return document.queryselectorall(c || e);
if(i) return document.queryselectorall(i)[0];
}else{
if(c){
var all = document.getelementsbytagname(t || '*'),
cn = c.slice(1,c.length),
reg = new regexp('^'+cn+'\\b'), // 限定类名的起始,结束只要是相同字符结束即可。
em = [];
for(var i=0;i<all.length;i++){
if(reg.test(all[i].classname)){
em.push(all[i])
}
}
return em;
}else if(e){
return document.getelementsbytagname(e);
}else if(i){
return document.getelementbyid(i);
}
}
}else{
return undefined;
}
}
调用方式:
$('selector'[,type])