【发布时间】:2019-10-04 15:46:03
【问题描述】:
您好,我正在尝试将一些字符串从数组附加到表中。我希望每个数组项都有自己的 tr 元素。
到目前为止我尝试过的事情是这样的:
const body = document.body
const table = document.createElement('table')
const tr = document.createElement('tr')
const th = document.createElement('th')
const form = document.createElement('form')
const label = document.createElement('label')
table.innerHTML
body.append(table)
tr.innerHTML
table.append(tr)
const thText = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
thText.forEach((text)=>{
th.innerHTML = text
tr.append(th);
})
当console.log(th) 我得到<th> Actions </th> 6 次。但唯一呈现的是动作一次。
很想得到一些帮助。谢谢:)
【问题讨论】:
-
th指的是一个单一的元素。您的forEach一遍又一遍地修改和重新附加相同元素的文本。考虑类似cloneNode()。 -
或将
.createElement("th")移动到.forEach()回调中
标签: javascript iteration