IE不支持getElementsByClassName最终完美解决方案_基础知识
程序员文章站
2022-05-07 15:34:01
...
目前可以这么解决,判断浏览器支不支持这个方法,如果支持就不管;如果不支持,就在document对象里加入getElementsByClassName这个方法,这样的写法有一个好处,即不管有没有原生函数你都不用去修改代码。
if(!document.getElementsByClassName){
document.getElementsByClassName = function(className, element){
var children = (element || document).getElementsByTagName('*');
var elements = new Array();
for (var i=0; ivar child = children[i];
var classNames = child.className.split(' ');
for (var j=0; jif (classNames[j] == className){
elements.push(child);
break;
}
}
}
return elements;
};
}
最终的方案为:
var getElementsByClassName = function (searchClass, node,tag) {
if(document.getElementsByClassName){
var nodes = (node || document).getElementsByClassName(searchClass),result = [];
for(var i=0 ;node = nodes[i++];){
if(tag !== "*" && node.tagName === tag.toUpperCase()){
result.push(node)
}else{
result.push(node)
}
}
return result
}else{
node = node || document;
tag = tag || "*";
var classes = searchClass.split(" "),
elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
patterns = [],
current,
match;
var i = classes.length;
while(--i >= 0){
patterns.push(new RegExp("(^|\s)" + classes[i] + "(\s|$)"));
}
var j = elements.length;
while(--j >= 0){
current = elements[j];
match = false;
for(var k=0, kl=patterns.length; kmatch = patterns[k].test(current.className);
if (!match) break;
}
if (match) result.push(current);
}
return result;
}
}
通常先使用getElementsByTagName("*")取出文档中所有元素,然后进行遍历,使用正则表达式找出匹配的元素放入一个数组返回。由于IE5不支持document.getElementsByTagName("*"),要使用分支document.all以防错误
下面的方法完美支持了document写法
复制代码 代码如下:
if(!document.getElementsByClassName){
document.getElementsByClassName = function(className, element){
var children = (element || document).getElementsByTagName('*');
var elements = new Array();
for (var i=0; i
var classNames = child.className.split(' ');
for (var j=0; j
elements.push(child);
break;
}
}
}
return elements;
};
}
最终的方案为:
复制代码 代码如下:
var getElementsByClassName = function (searchClass, node,tag) {
if(document.getElementsByClassName){
var nodes = (node || document).getElementsByClassName(searchClass),result = [];
for(var i=0 ;node = nodes[i++];){
if(tag !== "*" && node.tagName === tag.toUpperCase()){
result.push(node)
}else{
result.push(node)
}
}
return result
}else{
node = node || document;
tag = tag || "*";
var classes = searchClass.split(" "),
elements = (tag === "*" && node.all)? node.all : node.getElementsByTagName(tag),
patterns = [],
current,
match;
var i = classes.length;
while(--i >= 0){
patterns.push(new RegExp("(^|\s)" + classes[i] + "(\s|$)"));
}
var j = elements.length;
while(--j >= 0){
current = elements[j];
match = false;
for(var k=0, kl=patterns.length; k
if (!match) break;
}
if (match) result.push(current);
}
return result;
}
}