[英]how to iterate over list of items in html with list constructed in a javascript?
我有一个 JS,我像这样准备我的 div:
JS
function foo()
{
const a = 4;
const b = 'Hello'
document.getElementById('id-a').innerHTML = a;
document.getElementById('id-b').innerHTML = b;
}
后来在我的 html 中,我在下面做,它给出了值。
<h1><div id='id-a'></div></h1>
<h1><div id='id-b'></div></h1>
到目前为止,一切都很好。 现在我希望有一个项目列表并迭代这样:
function bar()
{
var myList = [];
for (i=0; i<10; i++)
{
var d = {"i":i, "s":'this is my stiring'}
myList.push(d);
}
}
问题,我如何在一个看起来像这样的表上迭代它?
<table>
<tr>
<th>index</th>
<th>string</th>
<tr>
//here must come a for loop to iterate over the 'myList'
<td>?</td>
<td>?</td>
</tr>
我无法弄清楚在不同的 html 文件中迭代所需的 JS 或 JQuery 是什么(就像我最初提出的过程一样)。
你可以试试这个
function bar() { let tbBody = ''; for (i=0; i<10; i++) { tbBody+=`<tr><td>${i}</td><td>this is my string</td></tr>` } document.getElementById("tb-body").innerHTML = tbBody } bar();
<table> <thead> <th>index</th> <th>string</th> </thead> <tbody id="tb-body"> </tbody> </table>
如果将 'A' 和 'B' class 名称添加到要循环的标签中,则可以使用document.getElementsByClassName([your_class_name])
。 function 看起来像这样:
<table>
<tr>
<th>index</th>
<th>string</th>
<tr>
//here must come a for loop to iterate over the 'myList'
<td class="my-list-class-a">?</td>
<td class="my-list-class-b">?</td>
</tr>
function bar()
{
var myListA = document.getElementByClassName('my-list-class-a');
var myListB = document.getElementByClassName('my-list-class-b');
for (i=0; i<10; i++)
{
myListA[i].innerHTML = i;
myListB[i].innerHTML = 'this is my string';
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.