如何在 javascript 函数中使用 getElementsByClassName? [英] How to use getElementsByClassName in javascript-function?
问题描述
我不知道如何在 JavaScript 中使用多个 ID.单个 ID 和 getElementById
没有问题,但是一旦我将 ID 更改为类并尝试使用 getElementsByClassName
,该函数就会停止工作.我已经阅读了大约 100 篇关于该主题的帖子;仍然没有找到答案,所以我希望这里有人知道如何使 getElementsByClassName
工作.
I can't 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. I've read about a 100 post about the topic; still haven't found the answer, so I hope someone here knows how to make getElementsByClassName
work.
这是我用于测试的一些简单代码:
Here's 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()
返回一个 nodeList
HTMLCollection代码>*.您试图直接对结果进行操作;您需要遍历结果.
getElementsByClassName()
returns a nodeList
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";
}
}
<小时>
* 更新以反映界面的变化
这篇关于如何在 javascript 函数中使用 getElementsByClassName?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!