简体   繁体   English

使用在IE 8和7中不起作用的类获取标签

[英]Get tag using class not working in IE 8 & 7

My Script 我的剧本

var cwidth   = document.getElementById('contentarea').clientWidth;
var elements = document.getElementsByClassName("shadow");

for(var i=0; i<elements.length; i++) {
   elements[i].style.width = cwidth+"px";
   var anc = elements[i].getElementsByTagName("a"); // not working in IE 7 & 8
   anc[0].style.width = cwidth+"px";
}

This script working well in all browsers except IE 7 & 8 该脚本在IE 7和8以外的所有浏览器中均能正常运行

Any one please help me 有人请帮我

getElementsByClassName isn't supported in IE<9. IE <9不支持getElementsByClassName

In IE8 you can use: 在IE8中,您可以使用:

var elements = document.querySelectorAll(".shadow");

But keep in mind that it's not a live collection like the one you get with getElementsByClassName . 但是请记住,它不是像通过getElementsByClassName获得的实时集合。 And if you want to look for elements with multiple classes, you'll have to do document.querySelectorAll(".first.second"); 并且,如果要查找具有多个类的元素,则必须执行document.querySelectorAll(".first.second"); .

As for IE7, you have to rely on something else, like a weel known framework (like jQuery or just Sizzle), or a function like this: 至于IE7,您必须依靠其他东西,例如众所周知的框架(例如jQuery或Sizzle)或类似这样的函数:

var getElementsByClassName = (function(all) {
    return function (cls) {
        var a = [], i = 0;
        for (; i < all.length; i++)
            if ((" " + all[i].className + " ").indexOf(" " + cls + " ") !== -1)
                a.push(all[i]);
        return a;
    };
})(document.all);

This isn't a live collection either, moreover you won't be able to search for elements with multiple classes. 这也不是一个实时集合,而且您将无法搜索具有多个类的元素。 That is, unless they are ordered like you want in their className property, but you can't rely on that. 也就是说,除非在className属性中按照您的需要对其进行排序,但是您不能依赖className You'll have to do something more complicated, I'll leave it to you when you'll get more experienced in Javascript. 您将不得不做一些更复杂的事情,当您对Java有更多的经验时,我会把它留给您。

IE7和8没有功能'getElementsByClassName',您可以像jQuery一样自行构建此功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM