我的表格代码是:
这是我的JSfiddle
function insert_Row() {
var xTable = document.getElementById('partsTable');
var tr = document.createElement('tr');
tr.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>";
xTable.appendChild(tr);
}
<table class="table table-bordered table-striped" id="partsTable">
<thead>
<tr class="bg-primary">
<th colspan=2>Services</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control'> </td>
<td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control'></td>
</tr>
<tr>
<td colspan=3><button onclick="insert_Row();">+</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="col-md-6">   </td>
<td><strong>Total</strong></td>
<td><strong>$1000.00</strong></td>
</tr>
</tfoot>
</table>
但它在tr
末尾添加了新的tbody
。我想在tr
之前添加tr
一个地方。这可能吗?
答案 0 :(得分:1)
有specific method用于在指定索引的表中创建和插入行:
function insert_Row()
{
var xTable = document.getElementById('partsTable');
var index = xTable.rows.length - 1;
var tr = xTable.insertRow(index);
tr.innerHTML = "<td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td>" ;
}
答案 1 :(得分:0)
您可以找到要插入新行的行。并使用insertAdjacentHTML
beforebegin
前置或beforeend
追加
function insert_Row(button)
{
var xTable=document.getElementById('partsTable');
var body = xTable.tBodies[0]
var rows = body.rows
// pick the last and prepend
rows[rows.length - 1].insertAdjacentHTML('beforebegin', "<tr><td colspan=2><input type='text' name='parts[]' placeholder='part 1' class='form-control' > </td><td><input type='text' name='price[]' placeholder='price e.g 100' class='form-control' ></td></tr>")
}
<table class="table table-bordered table-striped" id="partsTable">
<thead>
<tr class="bg-primary" >
<th colspan=2>Services</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan=2><input type='text' name="parts[]" placeholder="part 1" class='form-control' > </td>
<td><input type='text' name="price[]" placeholder="price e.g 100" class='form-control' ></td>
</tr>
<tr>
<td colspan=3><button onclick="insert_Row();">+</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td class="col-md-6">   </td>
<td><strong>Total</strong></td>
<td><strong>$1000.00</strong></td>
</tr>
</tfoot>
</table>