【问题标题】:Iterate and append to table迭代并追加到表
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    • 它创建并使用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>

    【讨论】:

      猜你喜欢
      • 2013-02-17
      • 2021-11-18
      • 1970-01-01
      • 2020-11-09
      • 2019-09-06
      • 2020-01-22
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多