迭代并追加到表

时间:2019-10-04 15:46:03

标签: javascript iteration

您好,我正在尝试将一些字符串从数组追加到表中。我希望每个数组项都有自己的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次。但是唯一呈现的是动作一次。
希望得到一些帮助。谢谢:)

2 个答案:

答案 0 :(得分:1)

您仅创建一个th元素。您需要为每个迭代创建一个,因此,在循环内:

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

答案 1 :(得分:0)

有几种不同的方法可以做到这一点。这是一种方法的示例。此方法所做的事情与您的示例有所不同。

  • 它创建并使用thead元素进行正确的表格式设置。
  • 它使用基本的for循环方法。
  • 它将为数组中的每个标头标签创建一个新的th元素,然后将其附加到tr元素中。
  • 它使用textContent而不是innerHTML

const headerLabels = ["ID", "First name", "Last name", "Email", "Phone number", "Actions"]
const body = document.body
const table = document.createElement('table')
const thead = document.createElement('thead')
const tr = document.createElement('tr')

thead.append(tr)
table.append(thead)
body.append(table)

for (let i = 0; i < headerLabels.length; i++)  {
    let th = document.createElement('th')
    th.textContent=headerLabels[i]
    tr.append(th)
}
td, th {
    border: 1px solid #ddd;
    padding: 8px;
}
  
tr:nth-child(even) {
 background-color: #f2f2f2;
}
  
th {
    padding-top: 12px;
    padding-bottom: 12px;
    text-align: left;
    background-color: #4CAF50;
    color: white;
}
<body>
    <script src="main.js"></script>
</body>