简体   繁体   English

Javascript:如何遍历值数组并创建表行

[英]Javascript: How to iterate through an array of values and create table rows

I am fetching data from a server, I would like to iterate through the values and display them into the first column of the table.我正在从服务器获取数据,我想遍历这些值并将它们显示到表的第一列中。 Any help that can steer me in the right direction would be appreciated.任何可以引导我走向正确方向的帮助将不胜感激。

Javascript Javascript

fetch(_____,{
}).then(data => {
    var mstone = data.MilName;

    var table = document.getElementById("milestone-table");
    var row = table.insertRow(table.rows.length);
    // var cell1 = row.insertCell(0);
    //var cell2 = row.insertCell(1);

    //cell1.setAttribute("style", "text-align:center");
    //cell2.setAttribute("style", "text-align:center");
    
    //Iterating through data values and trying to display onto table
    for(var i = 0; i < mstone.length; i++){
        var cell = row.insertCell(0);
        cell.setAttribute("style", "text-align:center");
        cell.innerHTML = mstone[i]; 
    }

}).catch(function(err){
    console.log("Fetch Problem: " + err);
});

You can set up the table in HTML without any of rows added, loop through the response data and add a row and cell for each item.您可以在 HTML 中设置表格而不添加任何行,循环访问响应数据并为每个项目添加行和单元格。

 const data = ['foo', 'bar', 'baz'] // Dummy response data const tbody = document.querySelector('tbody'); data.forEach(item => { const tr = tbody.insertRow(); tr.insertCell().innerText = item })
 <table> <thead> <tr> <th>Column Heading</th> </tr> </thead> <tbody> </tbody> </table>

Try some thing like below.试试下面的一些东西。 Have nested loops (1 for rows and 1 for columns)有嵌套循环(1 行,1 列)

 fetch("https://swapi.dev/api/planets/").then((res) => res.json()).then((resp) => { const results = resp.results; var table = document.getElementById("table"); for (let j = 0; j < 4; j++) { var row = table.insertRow(j); for (var i = 0; i < 4; i++) { var cell = row.insertCell(0); cell.setAttribute("style", "text-align:center; border: 1px solid blue;"); cell.innerHTML = Object.values(results[j])[i]; } } });
 <table id="table" style="border: 1px solid grey"></table>

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

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