this.class与this.getAttribute('class')

时间:2014-08-18 15:20:00

标签: javascript html

我有一个单选按钮,当按下它时会调用一个函数,它接受按钮的类作为参数。所以像这样:

<input class="myclass" type="radio" name="name" value="x" checked="true" onClick="myFunction(this.value, this.getAttribute('class'))"></input>

请注意,在我的onClick中,我有this.getAttribute('class')而不是this.class。我尝试使用this.class但我不断获得undefinedthis.class不可接受吗?我在我的代码中的其他地方使用了this.id,但是由于某些原因,当我想引用类时,我需要使用getAttribute

基本上我问的是this.classthis.getAttribute('class')之间有什么区别?

2 个答案:

答案 0 :(得分:3)

没有this.class。我想你的意思是this.className。 看到这个:

getAttribute("class")更具普遍性,因为它可用于不同类型的文档。在XML文档中,最重要的是。包括SVG。

this.className仅适用于HTML

答案 1 :(得分:1)

使用className获取class属性的当前值。我认为这背后的原因是因为阶级是一个保留词。