你好我想通过鼠标悬停在上面得到类名。所有我现在得到悬停是类名:[objectHTMLCollection]。 我使用这个代码在HTML:的onmouseover = “类(这)”Javascript类名不会出现
function class() {
var x = document.getElementsByClassName("abc");
x[0].innerHTML = "Class name" + x + " ";
}
你好我想通过鼠标悬停在上面得到类名。所有我现在得到悬停是类名:[objectHTMLCollection]。 我使用这个代码在HTML:的onmouseover = “类(这)”Javascript类名不会出现
function class() {
var x = document.getElementsByClassName("abc");
x[0].innerHTML = "Class name" + x + " ";
}
我使用这个代码在HTML:的onmouseover = “类(这)”
在这种情况下,你应该为你的函数声明一个参数并使用它。元素的当前设置类名(S)是可以从它的className
属性:
function showClass(element) {
element.innerHTML = "Class name " + element.className;
}
另外请注意,我改变了函数的名称。 class
是JavaScript中的关键字,不能将其用作标识符。 (您需要accodingly更新onmouseover
。)
不要使用任何的reserved keywords在代码名称函数,变量等
你得到[objectHTMLCollection]
为toString()
方法的结果是被隐式调用时您正在尝试通过执行"Class name" + x + " ";
将x
(这是对象)转换为字符串。改为使用x[0].className
。
问题中代码中的'x.className'将被定义为'undefined.' –
确实,我错过了他正在获取一个集合。 –
这是因为'getElementsByClassName'选择*集合*,而不是*元素*。 –
http://stackoverflow.com/help/how-to-ask –
@ Quasimodo'sclone:公平地说,上面的代码的一半处理正确。 :-) –