【发布时间】:2017-10-09 07:50:21
【问题描述】:
我有这些 div(注释),我需要每个 div 有一个不同的 ID,我已经设法弄清楚如何给他们自己的唯一 ID,但现在我不知道如何获得它们。我可以使用我自己编写 ID 的手动功能来完成,但这不是一个好方法。因此,我正在努力获得 id 'rect',我在创建一个新的时每增加 1 个。所以 rect0、rect1、rect2 等等。 但是我如何在不使用:this function 100times 的情况下获得它们?
function update(jscolor) {
document.getElementById('rect0').style.backgroundColor = "#" + jscolor;
document.getElementById('rect1').style.backgroundColor = "#" + jscolor;
document.getElementById('rect2').style.backgroundColor = "#" + jscolor;
document.getElementById('rect3').style.backgroundColor = "#" + jscolor;
document.getElementById('rect4').style.backgroundColor = "#" + jscolor;
document.getElementById('rect5').style.backgroundColor = "#" + jscolor;
document.getElementById('rect6').style.backgroundColor = "#" + jscolor;
document.getElementById('rect7').style.backgroundColor = "#" + jscolor;
document.getElementById('rect8').style.backgroundColor = "#" + jscolor;
document.getElementById('rect9').style.backgroundColor = "#" + jscolor;
document.getElementById('rect10').style.backgroundColor = "#" + jscolor;
document.getElementById('rect11').style.backgroundColor = "#" + jscolor;
document.getElementById('rect12').style.backgroundColor = "#" + jscolor;
document.getElementById('rect13').style.backgroundColor = "#" + jscolor;
document.getElementById('rect14').style.backgroundColor = "#" + jscolor;
document.getElementById('rect15').style.backgroundColor = "#" + jscolor;
document.getElementById('rect16').style.backgroundColor = "#" + jscolor;
document.getElementById('rect17').style.backgroundColor = "#" + jscolor;
document.getElementById('rect18').style.backgroundColor = "#" + jscolor;
document.getElementById('rect19').style.backgroundColor = "#" + jscolor;
}
我试过在哪里得到矩形,然后像使用 ++ 一样递增,但它没有用,所以我希望有人知道一种有效的方法。
【问题讨论】:
-
请在此处添加代码,或 jsfiddle 链接,以便我们了解。
-
向您的元素添加一个类并定位该类。
-
i need each one to have a different ID这不太可能。使用类或布局结构找出适合 CSS 的目标组。 -
绝对同意@JethroHazelhurst,这就是大喊“大家好,我们去吃披萨!”的区别。和“嘿简,我们去吃披萨!嘿乔,我们去吃披萨!嘿阿尔伯特,我们去吃披萨!......”
-
@Hodrobond 我已经尝试过上课,但我不想改变颜色!在这里查看我的代码笔:codepen.io/Qbinx/pen/OmObRg?editors=1010
标签: javascript