我正在使用下面的 JS 代码,以便在单击链接时更改类。
document.getElementById("gifts").setAttribute("class", "gkvSprite selected");
这在 IE 中不起作用,但在 FF 和 Chrome 中有效。然后我将代码更改为:
document.getElementById("gifts").setAttribute("className", "gkvSprite selected");
然后它在 IE 中工作,但在 FF 和 Chrome 中停止工作。
有人可以帮帮我吗?
最佳答案
您可以可靠地使用 className
属性而不是 setAttribute
:
document.getElementById("gifts").className = "gkvSprite selected";
更一般地说,在 setAttribute
中有几个不同浏览器以不同方式对待的属性名称:class
vs className
,以及 for
与 htmlFor
。像 Prototype 这样的图书馆, jQuery ,等等将为您消除这些差异,尽管(再次)在 class
的特定情况下,您可以可靠地使用该属性。
关于javascript - 如何在 IE、FF、Chrome 等上可靠地设置类 attr w/JavaScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2490627/