简体   繁体   English

使用JavaScript在HTML表中添加行

[英]Add rows in HTML table with JavaScript

I'd like to write <td> tags with JavaSctipt in my HTML code. 我想在我的HTML代码中用JavaSctipt编写<td>标签。 I'm building a <table> in the main code and I'd like to continue it with a <script> , adding rows in the division. 我正在主代码中构建一个<table> ,并希望继续使用<script> ,在该部门中添加行。

<body>
  <table>
    <tr>
      <td>First</td>
    </tr>
    <div id="searchOutput"></div>
    <tr>
      <td>Last</td>
    </tr>
  </table>
  <script>
  document.getElementById("searchOutput").innerHTML = "<tr><td>Middle<td><tr>";
  </script>
</body>

The problem is that the <script> creates another table in a strange way. 问题在于<script>以一种奇怪的方式创建了另一个表。

铬结果 铬结果

Is there a way to add rows without writing all code (including <table> tags) in the <script> ? 有没有一种方法可以添加行而不在<script>编写所有代码(包括<table>标记)?

For insert new row in the table, you can use Table insertRow() and insertCell() Methods. 要在表中插入新行,可以使用Table insertRow()insertCell()方法。 The insertRow() methods creates an empty <tr> element and adds it to a table. insertRow()方法创建一个空的<tr>元素并将其添加到表中。 The insertCell() method inserts a cell into the current row. insertCell()方法将一个单元格插入当前行。

See the code below: 请参见下面的代码:

 function addRows() { var table = document.getElementById( 'myTable' ), row = table.insertRow(0), cell1 = row.insertCell(0), cell2 = row.insertCell(1); cell1.innerHTML = 'Cell 1'; cell2.innerHTML = 'Cell 2'; } 
 table { border: 1px solid #999; border-collapse: collapse; width: 100% } td { border: 1px solid #999 } 
 <p> <button onclick="addRows()">Add a new row</button> </p> <table id="myTable"></table> 

CertainPerformance is correct; 某些性能是正确的; divs should not be direct children of tables. div不应是表的直接子级。 You might find this question useful. 您可能会发现此问题有用。 You have the right idea, if only you could actually replace the HTML of the div as opposed to simply filling it in. So, you could set the ID of the Last tr to searchOutput. 您有一个正确的想法,即只要您实际上可以替换div的HTML而不是简单地将其填充即可。因此,您可以将Last tr的ID设置为searchOutput。 Then, something like 然后,类似

var newRow = document.createElement("tr");
var oldRow = document.getElementById("searchOutput");
newRow.innerHTML = "<tr><td>Middle</td></tr>";
document.getElementByTagName("table").insertBefore(row, oldRow);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM