问题描述
我不知道如何在javascript中使用多个ID。单个ID和getElementById没有问题,但是一旦我将ID更改为类,并尝试使用getElementsByClassName,该功能将停止工作。我读了关于这个话题的100个帖子;仍然没有找到答案,所以我希望有人在这里知道如何使getElementsByClassName工作。还有一些我用来测试的简单代码:
function change(){
document.getElementById('box_one')。style.backgroundColor =blue;
}
函数change_boxes(){
document.getElementsByClassName('boxes')。style.backgroundColor =green;
}
< input name =type =buttononClick =change(document.getElementById('box_one')); change_boxes(document.getElementsByClassName 'boxes'))value =点击/>
< div id =box_one>< / div>
< div class =boxes>< / div>
< div class =boxes>< / div>
getElementsByClassName() code>返回一个
HTMLCollection
*。你正在试图直接对结果进行操作;你需要遍历结果。
function change_boxes(){
var boxes = document.getElementsByClassName('boxes '),
i = boxes.length;
while(i--){
boxes [i] .style.backgroundColor =green;
}
}
* 更新以反映接口
之间的更改
I cant figure out how to use multiple IDs in javascript. No problem with single ID and getElementById, but as soon as i change IDs to class and try using getElementsByClassName the function stops working. Ive read about a 100 post about the topic; still havent found the answer so i hope someone here know how to make getElementsByClassName work.
Heres some simple code that i have used for testing:
function change(){
document.getElementById('box_one').style.backgroundColor = "blue";
}
function change_boxes(){
document.getElementsByClassName ('boxes').style.backgroundColor = "green";
}
<input name="" type="button" onClick="change(document.getElementById('box_one')); change_boxes(document.getElementsByClassName('boxes'))" value="Click" />
<div id="box_one"></div>
<div class="boxes" ></div>
<div class="boxes" ></div>
getElementsByClassName()
returns a HTMLCollection
*. You are trying to operate directly on the result; you need to iterate through the results.
function change_boxes() {
var boxes = document.getElementsByClassName('boxes'),
i = boxes.length;
while(i--) {
boxes[i].style.backgroundColor = "green";
}
}
* updated to reflect change in interface
这篇关于如何在javascript函数中使用getElementsByClassName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!