简体   繁体   English

如何循环td_i.innerHTML =消息;

[英]How can I loop td_i.innerHTML = message;

My code. 我的代码。

td_0.innerHTML = message;
td_1.innerHTML = message;
td_2.innerHTML = message;

How can I loop to this? 我该如何循环呢?

for (var i = 0; i < VarNames.length; i++) {
    td_i.innerHTML = message;
}

May be the following can help you out: 可能以下内容可以帮助您:

 var tds = document.querySelectorAll('td') var message = 'Test Data'; for (var i = 0; i < tds.length; i++) { tds[i].innerHTML = message + i; } 
 <table id="myTable"> <tr> <td></td> <td></td> <td></td> </tr> </table> 

<table id="tableID">
<tr>
<td>my td</td>
</tr>
</table>

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   //iterate through rows
   //rows would be accessed using the "row" variable assigned in the for loop
   for (var j = 0, col; col = row.cells[j]; j++) {
     //iterate through columns
     //columns would be accessed using the "col" variable assigned in the for loop
        col.innerHTML = message;
   }  
}

You could use document.querySelectorAll() and then Array.prototype.forEach() 您可以使用document.querySelectorAll() ,然后使用Array.prototype.forEach()

 document .querySelectorAll('#tableID tr td') .forEach((td, i) => td.innerHTML = 'Element ' + i); 
 <table id="tableID"> <tr> <td>td 1</td> </tr> <tr> <td>td 2</td> </tr> <tr> <td>td 3</td> </tr> </table> 

I know I'm blindly answering the question without helping the real goal behind the ask but just for reference, it is possible to loop some global variable names via the window object: 我知道我盲目地回答了这个问题,而无助于Ask背后的真正目标,但仅供参考,可以通过window对象循环一些全局变量名称:

for (var i = 0; i < VarNames.length; i++) {
    window[`td_${i}`].innerHTML = message;
}

The above code is just to show looping over variables that contains a variable in their names. 上面的代码只是显示循环遍历包含其名称中的变量的变量。 I wouldn't do it in real code. 我不会在真实代码中这样做。 Like other answers mentioned, it's better to get your elements into an iterable object with querySelectorAll() , so you don't have to declare individual variables for each element. 像提到的其他答案一样,最好使用querySelectorAll()将元素放入可迭代的对象中,因此不必为每个元素声明单独的变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM