我有一個基本的表結構:
<tr>
<th>ID</th>
<th>Name</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
</td>
我的javascript函式:
function newRow() {
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var lastRow = tbodyRef.rows[tbodyRef.rows.length - 1];
var lastCell = lastRow.cells[lastRow.cells.length -1];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
newCell.innerHTML = lastCell.id ;
newCell = newRow.insertCell();
newCell.innerHTML = "Alex";
}
當前呼叫該函式僅在 ID 列中生成“0”,如何增加它?
uj5u.com熱心網友回復:
嘗試運行以下命令:
function newRow() {
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var lastRow = tbodyRef.rows[tbodyRef.rows.length - 1];
var lastCell = lastRow.cells[lastRow.cells.length - 1];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
newCell.innerHTML = lastRow.rowIndex 1;
newCell = newRow.insertCell();
newCell.innerHTML = "Alex";
}
JS Fiddle 的作業示例:http: //jsfiddle.net/o30gxeda/1/
uj5u.com熱心網友回復:
檢查我使用的下面的代碼片段Template Literals和querySelector()方法,用簡單的方法來實作和計算rows length和increment by 1。
有用的鏈接:
https ://www.w3schools.com/js/js_string_templates.asp
https://www.w3schools.com/jsref/met_document_queryselector.asp
function newRow() {
var tbodyRef = document.querySelector('#myTable tbody');
tbodyRef.innerHTML =`
<tr>
<td>${tbodyRef.rows.length 1}</td>
<td>Alex</td>
</tr>`;
}
<table id="myTable" width="100%" border="1" cellpadding="10" cellspacing="0">
<thead>
<tr>
<th align="left">ID</th>
<th align="left">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
</tr>
</tbody>
</table>
<br>
<button type="button" onclick="newRow()">Add New Records</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489626.html
標籤:javascript html
上一篇:在Reactjs中等待一個承諾
