如何将一行作为倒数第二行插入


有很多

类似的问题,但我能找到的每一个问题都是使用jQuery,我想缓解这个问题。插入行的内容将动态创建。我的破碎方法:

function addRow() {
  let newRow = '<tr><td>Boo</td><td>✔</td><td></td><td>✔</td></tr>';
  document.getElementById('new').insertBefore(newRow);
}
body {
    padding: 50px;
    font-family: sans-serif;
}
table, th, td {
    border: 1px solid #000;
    border-collapse: collapse;
}
th, td {
    padding: 15px;
}
th {
    text-transform: capitalize;
}
#new {
    text-align: center;
    font-weight: bold;
}
#new:hover {
    cursor: pointer;
    background-color: grey;
    color: #fff;
}
<table>
  <tbody>
    <tr>
      <th>title</th>
      <th>multiple</th>
      <th>required</th>
      <th>special</th>
    </tr>
    <tr>
      <td>Bar</td>
      <td>✔</td>
      <td>✔</td>
      <td>✔</td>
    </tr>
    <tr>
      <td>Foo</td>
      <td>✔</td>
      <td></td>
      <td>✔</td>
    </tr>
    <tr>
      <td id="new" colspan="6" onClick="addRow">ADD NEW SETTING</td>
    </tr>
  </tbody>
</table>

如果您认为应该以不同的方式完成,请随意优化代码。

您可以使用

insertAdjacentHTML

function addRow() {
  let newRow = '<tr><td>Boo</td><td>✔</td><td></td><td>✔</td></tr>';
  document.getElementById('new').parentElement.insertAdjacentHTML('beforebegin', newRow)
}
body {padding: 50px; font-family: sans-serif;}
table, th, td {border: 1px solid #000; border-collapse: collapse;}
th, td {padding: 15px;}
th {text-transform: capitalize;}
#new {text-align: center; font-weight: bold;}
#new:hover {cursor: pointer; background-color: grey; color: #fff;}
<table>
  <tbody>
    <tr>
      <th>title</th><th>multiple</th><th>required</th><th>special</th>
    </tr>
    <tr>
      <td>Bar</td><td>✔</td><td>✔</td><td>✔</td>
    </tr>
    <tr>
      <td>Foo</td><td>✔</td><td></td><td>✔</td>
    </tr>
    <tr>
      <td id="new" colspan="6" onClick="addRow()">ADD NEW SETTING</td>
    </tr>
  </tbody>
</table>

  • 我只是删除了html和css中的换行符以降低答案高度,内容相同。

正如@Teemu所建议的,最好使用 HTMLTable 接口而不是使用 HTML 字符串:

function addRow() {
  const table = document.getElementById('dictionary');
  
  let text = ['Boo', undefined, '✔', '✔'];
  let row = table.insertRow(table.rows.length-1);
  
  for (let i = 0; i < table.rows[0].cells.length; i++) {
    row.insertCell(-1).textContent = text[i] || '';
  }
 }
body {padding: 50px; font-family: sans-serif;}
table, th, td {border: 1px solid #000; border-collapse: collapse;}
th, td {padding: 15px;}
th {text-transform: capitalize;}
#new {text-align: center; font-weight: bold;}
#new:hover {cursor: pointer; background-color: grey; color: #fff;}
<table>
  <tbody id="dictionary">
    <tr>
      <th>title</th><th>multiple</th><th>required</th><th>special</th>
    </tr>
    <tr>
      <td>Bar</td><td>✔</td><td>✔</td><td>✔</td>
    </tr>
    <tr>
      <td>Foo</td><td>✔</td><td></td><td>✔</td>
    </tr>
    <tr>
      <td id="new" colspan="6" onClick="addRow()">ADD NEW SETTING</td>
    </tr>
  </tbody>
</table>

如果快速和肮脏对您的项目来说很好,请参阅下面的答案 - 它工作得很好。

最新更新