Javascript 迭代并追加到表中

Javascript 迭代并追加到表中,javascript,iteration,Javascript,Iteration,您好,我正在尝试将数组中的一些字符串附加到表中。我希望每个数组项都有自己的tr元素 到目前为止,我尝试的是: const body=document.body const table=document.createElement('表') const tr=document.createElement('tr') const th=document.createElement('th') const form=document.createElement('form') const label

您好,我正在尝试将数组中的一些字符串附加到表中。我希望每个数组项都有自己的tr元素

到目前为止,我尝试的是:

const body=document.body
const table=document.createElement('表')
const tr=document.createElement('tr')
const th=document.createElement('th')
const form=document.createElement('form')
const label=document.createElement('label')
table.innerHTML
body.append(表)
tr.innerHTML
表2.3追加(tr)
const thText=[“ID”、“名字”、“姓氏”、“电子邮件”、“电话号码”、“操作”]
thText.forEach((文本)=>{
th.innerHTML=文本
tr.append(th);

})
您只创建了一个
th
元素。您需要为每个迭代创建一个,因此,在循环中:

thText.forEach(text => {
  const th = document.createElement('th')
  th.innerHTML = text
  tr.append(th)
})

有几种不同的方法可以做到这一点。这里有一个单向的例子。此方法与您的示例有一些不同之处

  • 它创建并使用
    thead
    元素进行适当的表格格式设置
  • 它使用基本的for循环方法
  • 它为数组中的每个标题标签创建一个新的
    th
    元素,然后将其附加到
    tr
    元素
  • 它使用
    textContent
    而不是
    innerHTML
const headerLabels=[“ID”、“名字”、“姓氏”、“电子邮件”、“电话号码”、“操作”]
const body=document.body
const table=document.createElement('表')
const thead=document.createElement('thead')
const tr=document.createElement('tr')
附加指令(tr)
表.追加(thead)
body.append(表)
for(设i=0;i
td,th{
边框:1px实心#ddd;
填充:8px;
}
tr:n个孩子(偶数){
背景色:#F2F2;
}
th{
填充顶部:12px;
垫底:12px;
文本对齐:左对齐;
背景色:#4CAF50;
颜色:白色;
}

th
指的是单个元素。您的
forEach
反复修改同一元素的文本并重新追加该元素。考虑一些类似的事情,或者移动<代码>。CuraEngEnter(“TH”)<代码>进入<代码>