如何在JS的循环中使用ID名称?

时间:2019-05-17 13:27:49

标签: javascript id

我正在尝试用Javascript做游戏。

在某些地方42 span应该随机分配颜色。

我猜我的代码由于以下部分而无法正常工作:

document.getElementById('s\'i\'').style.backgroundColor = color[c];

我希望有一种使用ID名称循环的方法

var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
var i;
for (i = 1; i <= 42; i++) {
  document.getElementById('demo').innerHTML = getRndInteger(0, 6);
  document.getElementById('s\'i\'').style.backgroundColor = color[c];
}

function getRndInteger(min, max) {
  var c = Math.floor(Math.random() * (max - min)) + min;
}
<span id="s1">s1</span><span id="s2">s2</span>
<span id="s3">s3</span><span id="s4">s4</span> ...

<span id="s40">s40</span> <span id="s41">s41</span><span id="s42">s42</span>

2 个答案:

答案 0 :(得分:2)

我假设我有42个<span>中有4个<span>

  var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
  var i;
  for (i = 1; i <= 4; i++) { 
    document.getElementById('demo').innerHTML = getRndInteger(0,6);
    document.getElementById('s'+i).style.backgroundColor = color[getRndInteger(0,6)];
  }

  function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
  }
<span id="s1">s1</span>
<span id="s2">s2</span>
<span id="s3">s3</span>
<span id="s4">s4</span>

<span id="demo">Demo</span>

答案 1 :(得分:0)

如果您对以下代码有疑问,请告诉我。

首先,您可以为所有元素提供相同的类。这样,您可以获得每个引用。此外,如果您愿意,它还可以通过添加span来添加更多元素。因此,如果您从42变为43,则无需修改循环条件。

function getRndInteger(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

// Wait for all DOMs to be loaded prior to run the code
document.addEventListener("DOMContentLoaded", function(event) { 
  document.getElementById('demo').innerHTML = getRndInteger(0,6);      
  var colors = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"]; 
  var elems = document.getElementsByClassName("elems");
  for(var i = 0; i < elems.length; ++i){
    var index = getRndInteger(0,6);
    var elem = elems.item(i);
    elem.style.backgroundColor = colors[index];
  }
});
<span class="elems" id="s1">s1</span>
<span class="elems" id="s2">s2</span>
<span class="elems" id="s3">s3</span>
<span class="elems" id="s4">s4</span>
<span class="elems" id="s5">s5</span>
<span class="elems" id="s6">s6</span>
<span class="elems" id="s7">s7</span>
<span class="elems" id="s8">s8</span>
<span class="elems" id="s9">s9</span>
<span class="elems" id="s10">s10</span>
<div id="demo"></div>