簡體   English   中英

如何從對象數組創建 HTML 表格?

[英]How to create an HTML table from an array of objects?

我需要從一組對象生成一個表。

例如,數組是:

let arr = [{name: 'Player1',score:10},
{name: 'Player2',score: 7},
{name: 'Player3',score:3}]

HTML 輸出應該是:

姓名 分數
播放器1 10
播放器2 7
播放器3 3

我想不出通過 vanilla JS 實現這一目標的方法。 另外,創建表格后,我將如何對其應用 CSS?

任何幫助,將不勝感激。

您可以循環遍歷數組,並為每個元素添加一行到新偽造的表中,該表將在最后添加到文檔中。

這是一個演示:

 let players = [ {name: 'Player1',score:10}, {name: 'Player2',score: 7}, {name: 'Player3',score:3} ]; const newTable = document.createElement("table"); newTable.innerHTML = "<thead><th>Player</th><th>Score</th></thead>"; for(player of players){ const newRow = document.createElement("tr"); const tdPlayer = document.createElement("td"); const tdScore = document.createElement("td"); tdPlayer.textContent = player.name; tdScore.textContent = player.score; newRow.appendChild(tdPlayer); newRow.appendChild(tdScore); newTable.appendChild(newRow); } const target = document.getElementById('target'); target.appendChild(newTable);
 table{ border: solid 1px black; } table td{ border: solid 1px black; }
 <div id="target"> </div>

你可以使用類似的東西

<body>
<div class="main-container">
    <table>
        <thead>
            <tr>
                <th>player</th>
                <th>score</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>
<script>
    const data = [{ name: 'Player 1', score: 10 },
    { name: 'Player 2', score: 7 },
    { name: 'Player 3', score: 3 }]

    const table = document.querySelector('tbody')
    data.forEach((item) => {
        table.innerHTML = table.innerHTML + `<tr>
                <td>${item.name}</td>
                <td>${item.score}</td>
            </tr>`
    })
</script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM