javascript getElementsByClassName IE 解析问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4404154/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
getElementsByClassName IE resolution issue
提问by Ryan Sharp
I am having issues figuring out how to resolve the getElementsByClassName issue in IE. How would I best implement the robert nyman (can't post the link to it since my rep is only 1) resolution into my code? Or would a jquery resolution be better? my code is
我在弄清楚如何解决 IE 中的 getElementsByClassName 问题时遇到问题。我将如何最好地将 robert nyman(无法发布指向它的链接,因为我的代表只有 1)解析到我的代码中?或者 jquery 分辨率会更好吗?我的代码是
function showDesc(name) {
var e = document.getElementById(name);
//Get a list of elements that have a class name of service selected
var list = document.getElementsByClassName("description show");
//Loop through those items
for (var i = 0; i < list.length; ++i) { 
    //Reset all class names to description
    list[i].className = "description";
}
if (e.className == "description"){
    //Set the css class for the clicked element
    e.className += " show";
}
else{
    if (e.className == "description show"){
        return;
    }
}}
and I am using it on this page dev.msmnet.com/services/practice-managementto show/hide the description for each service (works in Chrome and FF). Any tips would be greatly appreciated.
我在这个页面dev.msmnet.com/services/practice-management上使用它来显示/隐藏每个服务的描述(适用于 Chrome 和 FF)。任何提示将非常感谢。
采纳答案by karim79
I was curious to see what a jQuery version of your function would look like, so I came up with this:
我很好奇你的函数的 jQuery 版本会是什么样子,所以我想出了这个:
function showDesc(name) {
    var e = $("#" + name);
    $(".description.show").removeClass("show");
    if(e.attr("class") == "description") {
        e.addClass("show");
    } else if(e.hasClass("description") && e.hasClass("show")) {
        return;
    }
}
回答by alex
This should support multiple classes.
这应该支持多个类。
function getElementsByClassName(findClass, parent) {
  parent = parent || document;
  var elements = parent.getElementsByTagName('*');
  var matching = [];
  for(var i = 0, elementsLength = elements.length; i < elementsLength; i++){
    if ((' ' + elements[i].className + ' ').indexOf(findClass) > -1) {
      matching.push(elements[i]);
    }
  }
  return matching;
}
You can pass in a parent too, to make its searching the DOM a bit faster.
你也可以传入一个父对象,让它更快地搜索 DOM。
If you want getElementsByClassName('a c')to match HTML <div class="a b c" />then try changing it like so...
如果你想getElementsByClassName('a c')匹配 HTML<div class="a b c" />然后尝试像这样改变它......
var elementClasses = elements[i].className.split(/\s+/),
    matchClasses = findClass.split(/\s+/), // Do this out of the loop :)
    found = 0;
for (var j = 0, elementClassesLength = elementClasses.length; j < elementClassesLength; j++) {
    if (matchClasses.indexOf(elementClasses[j]) > -1) {
        found++;
    }
}
if (found == matchClasses.length) {
   // Push onto matching array
}
If you want this function to only be available if it doesn't already exist, wrap its definition with
如果您希望此函数仅在它不存在时可用,请将其定义用
if (typeof document.getElementsByClassName != 'function') { }
回答by Jeff B
Even easier jQuery solution:
更简单的 jQuery 解决方案:
$('.service').click( function() {
    var id = "#" + $(this).attr('id') + 'rt';
    $('.description').not(id).hide();
    $( id ).show();
}
Why bother with a showclass if you are using jQuery?
show如果您正在使用 jQuery,为什么还要为一个类而烦恼呢?
回答by patocardo
I used to implement HTMLElement.getElementByClassName(), but at least Firefox and Chrome, only find the half of the elements when those elements are a lot, instead I use something like (actually it is a larger function):
我曾经实现过HTMLElement.getElementByClassName(),但至少Firefox和Chrome,当这些元素很多时只能找到一半的元素,而不是我使用类似的东西(实际上它是一个更大的函数):
getElmByClass(clm, parent){
   // clm:  Array of classes
   if(typeof clm == "string"){ clm = [clm] }
   var i, m = [], bcl, re, rm;
   if (document.evaluate) {    // Non MSIE browsers
      v = "";
      for(i=0; i < clm.length; i++){
         v += "[contains(concat(' ', @"+clc+", ' '), ' " + base[i] + " ')]";
      }
      c = document.evaluate("./"+"/"+"*" + v, parent, null, 5, null);
      while ((node = c.iterateNext())) {
          m.push(node);
      }
   }else{                  // MSIE which doesn't understand XPATH
      v = elm.getElementsByTagName('*');
      bcl = "";
      for(i=0; i < clm.length; i++){
          bcl += (i)? "|":"";
          bcl += "\b"+clm[i]+"\b";
      }
      re = new RegExp(bcl, "gi");
      for(i = 0; i < v.length; i++){
         if(v.className){
             rm = v[i].className.match(bcl);
             if(rm && rm.length){      // sometimes .match returns an empty array so you cannot use just 'if(rm)'
                 m.push(v[i])
             }
         }
      }
    }
    return m;
}
I think there would be a faster way to iterate without XPATH, because RegExp are slow (perhaps a function with .indexOf, it shuld be tested), but it is working well
我认为在没有 XPATH 的情况下会有更快的迭代方法,因为 RegExp 很慢(也许是一个带有 .indexOf 的函数,它应该被测试),但它运行良好
回答by user1416526
Heres one I put together, reliable and possibly the fastest. Should work in any situation.
这是我放在一起的,可靠且可能是最快的。应该在任何情况下工作。
function $class(className) {
    var children = document.getElementsByTagName('*') || document.all;
    var i = children.length, e = [];
    while (i--) {
        var classNames = children[i].className.split(' ');
        var j = classNames.length;
        while (j--) {
            if (classNames[j] == className) {
                e.push(children[i]);
                break;
            }
        }
    }
    return e;
}
回答by JCOC611
You can replace getElementsByClassName()with the following:
您可以替换getElementsByClassName()为以下内容:
function getbyclass(n){
  var elements = document.getElementsByTagName("*");
  var result = [];
  for(z=0;z<elements.length;z++){
    if(elements[z].getAttribute("class") == n){
      result.push(elements[z]);
    }
  }
  return result;
}
Then you can use it like this:
然后你可以像这样使用它:
getbyclass("description") // Instead of document.getElementsByClassName("description")

