关于IE中getElementsByClassName不能用的问题
今天使用getElementsByClassName写了段小程序,满怀欣喜的准备去测试,在ff,谷歌等主流浏览器上测试都没问题,在IE9上也没问题,在IE6、8中测试的时候就出现问题了,浏览器报错。纠结了下代码,貌似没问题,果断找度娘。。。终于发现问题所在,然来是IE6、8中不支持getElementsByClassName这种方法。随后在网上搜索解决方法,找到了一个比较好的方法,是个老外写的一个方法,定睛一看居然是05年的问题了。。。先上代码:
/*Developed by Robert Nyman, http://www.robertnyman.comCode/licensing: http://code.google.com/p/getelementsbyclassname/*/var getElementsByClassName = function (className, tag, elm){if (document.getElementsByClassName) {getElementsByClassName = function (className, tag, elm) {elm = elm || document;var elements = elm.getElementsByClassName(className),nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,returnElements = [],current;for(var i=0, il=elements.length; i<il; i+=1){current = elements[i];if(!nodeName || nodeName.test(current.nodeName)) {returnElements.push(current);}}return returnElements;};}else if (document.evaluate) {getElementsByClassName = function (className, tag, elm) {tag = tag || "*";elm = elm || document;var classes = className.split(" "),classesToCheck = "",xhtmlNamespace = "http://www.w3.org/1999/xhtml",namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,returnElements = [],elements,node;for(var j=0, jl=classes.length; j<jl; j+=1){classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";}try{elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);}catch (e) {elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);}while ((node = elements.iterateNext())) {returnElements.push(node);}return returnElements;};}else {getElementsByClassName = function (className, tag, elm) {tag = tag || "*";elm = elm || document;var classes = className.split(" "),classesToCheck = [],elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),current,returnElements = [],match;for(var k=0, kl=classes.length; k<kl; k+=1){classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));}for(var l=0, ll=elements.length; l<ll; l+=1){current = elements[l];match = false;for(var m=0, ml=classesToCheck.length; m<ml; m+=1){match = classesToCheck[m].test(current.className);if (!match) {break;}}if (match) {returnElements.push(current);}}return returnElements;};}return getElementsByClassName(className, tag, elm);};
使用这个方法之后,IE6、8中能显示了,但是还是有个随机的问题,有时刷新几次又会报错,暂时无解了。然后我想用jquery能不能解决这个刷新报错的问题,当然用jquery也能替代getElementsByClassName这个方法,具体怎么用这里就不作介绍了。然而事实终不能如人愿,刷新还是会有问题,而且报错是随机的,有时第一次加载过程中就报错,有时刷新几次才报错。。。大侠们。。。求解决。。。