-3

我制作了一个脚本来为表格行着色。我的脚本仅适用于 Internet Explorer 8 或更高版本。如何使我的脚本跨浏览器?

window.onload = (function()
{
    "use strict";
    var c = 0, i, j, t = document.getElementsByTagName("tbody"), r;
    for(i = 0; i < t.length; i++)
    {
        r = t[i].getElementsByTagName("tr");
        for(j = 0; j < r.length; j++)
        {
            if(c%2 === 1)
            {
                r[j].setAttribute("class", "colored");
            }
            c++;
        }
        c = 0;
    }
});
4

1 回答 1

3

改变

r[j].setAttribute("class", "colorful");

r[j].className = "colorful";

IE 有出错的历史,setAttribute其中出错的方式之一与class属性有关。(在早期版本中,即使该属性被称为class,他们希望您className即使在使用时也调用它setAttribute,这是完全错误的。其他浏览器和更新版本的 IE 都正确。)

幸运的是,该class属性可靠地反映为被称为元素的属性className(在所有浏览器中),因此您可以通过转到反射属性来避开 IE 的setAttribute问题,如上所示。

for(元素上的属性也会发生同样的事情label,仅供参考;请改用htmlFor反射属性。)

于 2013-03-11T13:31:35.350 回答