如何使用Javascript在HTML中的表上创建新行?

时间:2015-11-14 20:16:28

标签: javascript html twitter-bootstrap

我正在尝试使用javascript函数创建一个新行。我已经回顾了之前回答的所有问题,但没有人帮助过。这是我的代码,如果这有助于任何:

var deleteRow = document.getElementsByClassName('gone');

function removeParent(){
  this.parentNode.parentNode.remove();
}

for(var i = 0; i < deleteRow.length; i++) {
  deleteRow[i].addEventListener("click", removeParent);
}

var addRow = document.getElementsByClassName('add');

function addRow(){
  var deleteRow = table.insertRow(0);
}

for(var i = 0; i < addRow.length; i++) {
  addRow[i].addEventListener("click", addRow);
}

1 个答案:

答案 0 :(得分:2)

试试这个code

function myCreateFunction() {
    var table = document.getElementById("myTable");
    var row = table.insertRow(0);
    var cell1 = row.insertCell(0);
    var cell2 = row.insertCell(1);
    cell1.innerHTML = "NEW CELL1";
    cell2.innerHTML = "NEW CELL2";
}

function myDeleteFunction() {
    document.getElementById("myTable").deleteRow(0);
}

并使用此html

<p>Click the buttons to create and delete row(s) for the table.</p>

<table id="myTable">
   <tr>
      <td>Row1 cell1</td>
      <td>Row1 cell2</td>
   </tr>
   <tr>
      <td>Row2 cell1</td>
      <td>Row2 cell2</td>
   </tr>
   <tr>
      <td>Row3 cell1</td>
      <td>Row3 cell2</td>
   </tr>
</table>

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>