一、选取元素
1,获取类(兼容ie6以上)
//普通做法 var x_getClass = function(className,node,tag) { var node = node || document; var tag = tag || "*"; if(document.getElementsByClassName) { return node.getElementsByClassName(className); } else { var allElem = node.getElementsByTagName(tag); var name = [], arr = []; var len = allElem.length; var xElem; for(var i = 0; i < len; i++) { xElem = allElem[i]; name = xElem.className.split(" "); for (var j = name.length; j >= 0; j--) { if(name[j] === className) { arr.push(xElem); break; //找到则跳出循环 } } } return arr; } }; //正则匹配 var x_getClass = function(className,node,tag) { var node = node || document; var tag = tag || "*"; if(document.getElementsByClassName) { return node.getElementsByClassName(className); } else { var allElem = node.getElementsByTagName(tag); var pattern = new RegExp("(^|\\s)"+className+"(\\s|$)"); var arr = []; var len = allElem.length; var xElem; //方式1:push到数组 for(var i = 0; i < len; i++) { xElem = allElem[i]; if ( pattern.test(xElem.className) ) { arr.push(xElem); } } //方法2:因为在同个循环里,代替push的做法更高效(作为公用的,这种用法最为推荐。) for(var i = 0,j=0; i < len; i++) { xElem = allElem[i]; if ( pattern.test(xElem.className) ) { arr[j] = xElem; j++; } }
return arr; } };
推荐这博客:http://www.cnblogs.com/rubylouvre/archive/2009/07/24/1529640.html (此博客最后总结的兼容ie5的方法没必要,牺牲效率)