Javascript跨浏览器

时间:2013-03-11 13:27:24

标签: javascript events internet-explorer-7

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

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;
    }
});

1 个答案:

答案 0 :(得分:3)

更改

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

r[j].className = "colorful";

IE有setAttribute错误的历史记录,其中一个错误的方法与class属性有关。 (在早期版本中,即使该属性被称为class,他们也希望您使用className来调用它setAttribute,这完全是错误的。其他浏览器和更新的版本IE浏览器,做对了。)

幸运的是,class属性可靠地反映在名为className的元素上的属性(在所有浏览器中),因此您可以支持IE的{{1}通过转到反射属性来解决问题,如上所示。

(同样的事情发生在setAttribute元素上的for属性,FYI;请改用label反射属性。)

相关问题