javascript this.class 与 this.getAttribute('class')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25366726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
this.class vs. this.getAttribute('class')
提问by pwerth
I have a radio button, and when it is pressed a function is called, which accepts the class of the button as an argument. So something like this:
我有一个单选按钮,当它被按下时,一个函数被调用,它接受按钮的类作为参数。所以像这样:
<input class="myclass" type="radio" name="name" value="x" checked="true" onClick="myFunction(this.value, this.getAttribute('class'))"></input>
Notice that in my onClick, I have this.getAttribute('class')
instead of simply this.class
. I tried using this.class but I kept getting undefined
. Is this.class
not an acceptable thing to do? I have used this.id
elsewhere in my code which works fine, but for some reason I need to use getAttribute
when I want to reference class.
请注意,在我的 onClick 中,我有this.getAttribute('class')
而不是简单的this.class
. 我尝试使用 this.class,但我一直得到undefined
. 是this.class
不是一件可以接受的事情?我this.id
在我的代码中的其他地方使用过它工作正常,但由于某种原因,getAttribute
当我想引用类时需要使用。
So essentially I am asking what is the difference between this.class
and this.getAttribute('class')
?
所以基本上我在问this.class
和之间有什么区别this.getAttribute('class')
?
采纳答案by E. Sundin
Use className to get the current value of the class attribute. I think the reason behind this is because class is a reserved word.
使用 className 获取类属性的当前值。我认为这背后的原因是因为 class 是一个保留字。
回答by Suchit kumar
There is no this.class
. i think you mean this.className
.
see this:
没有this.class
。我想你的意思是this.className
。看到这个:
getAttribute("class")
is more universal, because it can be used in different types of documents. In XML documents, most importantly. Including SVG.
getAttribute("class")
更通用,因为它可以用于不同类型的文档。在 XML 文档中,最重要的是。包括SVG。
this.className
works only in HTML
this.className
仅适用于 HTML