1 var regid = /^#([w-]*)$/, 2 regClass = /^.([w-]*)$/, 3 regName = /^(div|a|p|ul|li|input|select|document|body|iframe)$/, 4 regWhite = /s*/g; 5 //主要方法 6 function _B(name, doc) { 7 var selector, match, result = []; 8 var doctemp; 9 if (doc) { 10 doctemp = (typeof doc == "object" && doc.length > 0 && doc[0] && doc[0].nodeType || doc && doc.nodeType) ? doc : _B(doc); 11 } else { 12 doctemp = document; 13 } 14 selector = name && name.replace(regWhite, ""); 15 if (selector) { 16 match = regid.exec(selector); 17 if (match && match[1]) { 18 result = document.getElementById(match[1]); 19 } 20 match = regClass.exec(selector); 21 if (match && match[1]) { 22 var elems = doctemp.getElementsByTagName("*"); 23 var len = elems && elems.length || 0; 24 for (var i = 0; i < len; i++) { 25 var currentelem = elems[i]; 26 var classlist = currentelem.className.split(/s+/); 27 var classlen = classlist.length; 28 for (var j = 0; j < classlen; j++) { 29 if (classlist[j] == match[1]) { 30 result.push(currentelem); 31 break; 32 } 33 } 34 } 35 } 36 match = regName.exec(selector); 37 if (match && match[1]) { 38 result = doctemp.getElementsByTagName(match[1]); 39 } 40 } 41 return result ? result : null; 42 }
支持_B("#id") _B(".class") _B("div") _B("#id",dom) _B(".class",dom) _B("div" ,dom) dom默认是document