在现有表中添加行

时间:2016-07-07 14:54:30

标签: javascript html html-table

我可以知道如何在桌面中插入物品吗?我的代码似乎不起作用。

os.system( 'git push bitbucket master -p=mypassword' )
var tableRef = document.getElementById("myList").getElementsByTagName("tbody");

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = tableRef.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);

2 个答案:

答案 0 :(得分:2)

getElementsByTagName返回一个数组。您需要附加[0]以选择数组中的第一个元素。

你还试图在insertCell上使用tableRef,当你应该在newRow上使用它时:



var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

var newRow = tableRef.insertRow(tableRef.rows.length);

var newCell = newRow.insertCell(0);

var myTextTwo = "hello world";

var newText = document.createTextNode(myTextTwo);

newCell.appendChild(newText);

<table id="myList">
  <thead>
    <tr>
      <td>Product ID</td>
      <td>Product Name</td>
      <td>Quantity</td>
    </tr>
  </thead>
  <tbody>

  </tbody>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

要使其有效,您需要:

1)[0]放在.getElementsByTagName()后面,,因为此方法会返回一个元素数组,与.getElementById()不同,返回第一个实例:

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];

2)使用您想要单元格的行中的.insertCell(),在我们的案例newRow中,而不是在表格tbody上:

var newCell = newRow.insertCell(0);

您的正确JavaScript代码应为

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);

您还可以查看以下代码段

var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
#myList {
  border: 1px solid black;
}
#empty {
  border-bottom: 1px solid black;
}
<table id = "myList">
  <thead>
    <tr>
      <td>Product ID</td>
      <td>Product Name</td>
      <td>Quantity</td>
    </tr>

     <!--- This row is for adding a border-bottom line -->
    <tr>
      <td id = "empty" colspan  ="3"></td>
    </tr>
  </thead>
  <tbody>
    
  </tbody>
</table>

相关问题