如何在JavaScript中遍历数组并将元素添加至HTML表格(按钮触发)
修复方案
原有代码问题
- for循环未添加花括号包裹执行逻辑:仅
获取表格DOM这一行进入了循环,插入行、填充单元格的逻辑完全在循环外,只会执行一次 - 未按索引读取数组单个元素:直接把整个数组赋值给单元格,而非遍历到的当前元素
- HTML表格标签使用错误:表格表头容器应为
<thead>、页脚容器应为<tfoot>,而非页面级的<header>、<footer>标签
场景1:点击按钮一次性添加所有数组元素到表格
JS代码
function New_Item() { const Ingredients = ["Rigatoni", "Pesto", "Crushed Tomatoes", "Pasta Water", "Mozzarella Cheese", "Fresh Chopped Basil"] const table = document.getElementById("myTable"); // 循环逻辑用花括号包裹 for (var x = 0; x < Ingredients.length; x++) { const row = table.insertRow(-1); // -1表示插入到表格最后一行 const cell1 = row.insertCell(0); // 按索引取当前遍历到的单个元素 cell1.innerHTML = Ingredients[x]; } }
HTML代码
<table id="myTable"> <thead> <tr> <th>Ingredient</th> </tr> </thead> <tbody> </tbody> <tfoot> </tfoot> </table> <button type="button" onclick="New_Item()">Add Ingredient</button>
场景2:点击按钮依次添加单个元素(首次点击添加Rigatoni)
如果需要每次点击仅添加一个元素,可把数组提到函数外部,用计数器记录当前添加的位置:
JS代码
const Ingredients = ["Rigatoni", "Pesto", "Crushed Tomatoes", "Pasta Water", "Mozzarella Cheese", "Fresh Chopped Basil"] // 记录当前要添加的元素索引 let currentIndex = 0; function New_Item() { // 所有元素添加完成后终止执行 if(currentIndex >= Ingredients.length) return const table = document.getElementById("myTable"); const row = table.insertRow(-1); const cell1 = row.insertCell(0); cell1.innerHTML = Ingredients[currentIndex]; currentIndex++ }
HTML代码和场景1完全一致即可。
内容的提问来源于stack exchange,提问作者Eric Rubin
相关产品推荐
相关产品推荐

