我如何可靠地在IE,FF,Chrome等设置类attr w / JavaScript? [英] How can I reliably set the class attr w/JavaScript on IE, FF, Chrome, etc.?

查看:139
本文介绍了我如何可靠地在IE,FF,Chrome等设置类attr w / JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的JS代码,以便在单击链接时更改类。

  document.getElementById gift)。setAttribute(class,gkvSprite selected); 

这在IE中不起作用,但是在FF和Chrome中。然后我将代码更改为:

  document.getElementById(gifts)。setAttribute(className,gkvSprite selected ); 

然后它在IE中工作,但停止工作在FF和Chrome。

$ b $

解决方案

您可以可靠地使用 className 属性而不是 setAttribute

  document.getElementById(gifts)。className =gkvSprite selected; 

更一般地说,有一些属性名称,不同的浏览器在 setAttribute class vs className code>与 htmlFor 。图书馆如原型 jQuery ,等等将为您平滑这些差异,虽然(再次)在 class 的特定情况下,您可以可靠地使用该属性。


I am using the below JS code in order to change the class when a link is clicked.

document.getElementById("gifts").setAttribute("class", "gkvSprite selected");

This is not working in IE but it does in FF and Chrome. Then I changed the code to:

document.getElementById("gifts").setAttribute("className", "gkvSprite selected");

Then it worked in IE, but stopped working in FF and Chrome.

Could someone please help me out here?

解决方案

You can reliably use the className property instead of setAttribute:

document.getElementById("gifts").className = "gkvSprite selected";

More generally, there are a couple of attribute names that different browsers treat differently in setAttribute: class vs className, and for vs. htmlFor. Libraries like Prototype, jQuery, and the like will smooth out these differences for you, although (again) in the specific situation of class, you can reliably use the property instead.

这篇关于我如何可靠地在IE,FF,Chrome等设置类attr w / JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆