我有几个div标签trainingData0,trainingData1,trainingData2等我试图使用innerHTML来更新文本。
我试图用for循环引用它们但它不起作用。 (即使trainingDataDiv确实保存了正确的值,即trainingData0,如果我输入trainingData0.innerHTML,它会起作用)
有什么建议吗?提前谢谢。
<div id="trainingData0"></div>
---------------
for (var i=0; i<15; i++)
{
var trainingDataDiv = "trainingData" + i;
trainingDataDiv.innerHTML = data;
}
答案 0 :(得分:0)
Robby Cornelissen在我的问题评论中回答:)
for (var i=0; i<15; i++)
{
var trainingDataDiv = document.getElementById("trainingData" + i);
trainingDataDiv.innerHTML = data;
}
答案 1 :(得分:0)
因此,当您更改元素数量时,您无需更改最大数量:
//Get all elelemtns with ids that start with trainingData
var trainingDataDivs = document.querySelectorAll("[id^='trainingData']");
var data = "I'm training Data";
//iterate the elements we found earlier and update the data
for(var i = 0; i < trainingDataDivs.length; i++)
{
trainingDataDivs[i].innerHTML = data;
}
<div id="trainingData0"></div>
<div id="trainingData1"></div>
<div id="trainingData2"></div>
<div id="trainingData3"></div>
<div id="trainingData4"></div>
<div id="trainingData8"></div><!-- Note the gap in numbers -->
<div id="bob">I'm not training</div>
有关详细信息,请参阅Attribute selectors和querySelectorAll