为什么代码不起作用? [英] Why code doesn't works?
本文介绍了为什么代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么它不起作用?哪里出错?
Why it doesn't works? Where mistakes?
<body onload = "go()">
<div class = "elem"></div>
<button onclick = "go()">click to change bgcolor</button>
</body>
document.getElementsByClassName("elem").style.backgroundColor = "red";
div {
width: 100px;
height: 100px;
border: 2px solid black;
}
我的尝试:
请解释一下此代码中的错误。每当我第一眼看到代码时都可以,但是当我运行代码总是出错时,我现在没有什么不对。我很绝望。
What I have tried:
Please explain me what wrong in this code. Every time when I write code at first glance all right but when I run code always something wrong, and I don't now what wrong. I'm desperate.
推荐答案
getElementsByClassName()方法返回一个元素的子元素的集合,它具有指定的类名,作为NodeList对象。也就是说,JavaScript语法应如下所示,假设只有一个元素的类名为elem
"The getElementsByClassName() method returns a collection of an element's child elements with the specified class name, as a NodeList object." That said, the JavaScript syntax should look like below, assuming there only ONE element with class name "elem"
document.getElementsByClassName("elem")[0].style.backgroundColor = "red";
示例: CP_ChangeBgColor - JSFiddle [ ^ ]
参考:
HTML DOM getElementsByClassName()方法 [ ^ ]
getElementsByClassName返回一个数组,所以你必须去逐个粗略地设置元素并设置样式。
getElementsByClassName returns an array so you have to go through the elements one by one and set the style.
var els = document.getElementsByClassName("content-button");
for (var i = 0; i < els.length; i++)
{
els[i].style.backgroundColor = "red";
}
这篇关于为什么代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文