我有一个包含默认行的表格,我通过点击按钮动态添加新行,增加第一个tr
的{{1}}和innerText
的ID计数器。我想在删除一行后重新排列ID。假设我有5行,我删除了行nr 3,第4行应该有ID 3,第5行应该有ID 4等。而且当添加新行时,它应该重新排列行ID#s。
到目前为止我所拥有的。我一直在尝试,但没有成功或我没有得到预期的结果。谁能帮助我朝正确的方向发展?
td
添加行:
<table class="table text-center table-borderless" id="rfqTable" style="font-size: 12px;">
<thead>
<tr>
<th>Item</th>
<th>Descr</th>
<th>Quantity</th>
<th>One Time</th>
<th>Supplier</th>
</tr>
</thead>
<tbody>
<tr id="1" class="tableRow">
<td class="item">1</td>
<td><textarea name="item[1]" rows="3" cols="90" maxlength="500"></textarea></td>
<td><input type="number" name="amount[1]"/></td>
<td><input type="checkbox" name="oneTime[1]" value="1"></td>
<td><input type="checkbox" name="supplier[1]" value="1"></td>
</tr>
</tbody>
</table>
删除行:
var counter = 1;
var limit = 5;
document.getElementById("newItemBoxButton").addEventListener("click", function(){
if (counter == limit)
{
alert("Max row is 5!");
}
else
{
counter ++;
var table = document.getElementById("rfqTable");
var row = table.insertRow(-1);
row.setAttribute('id', counter );
var cell0 = row.insertCell(0);
cell0.innerHTML = counter;
cell0.setAttribute('id', 'item');
var cell1 = row.insertCell(1);
cell1.innerHTML = '<textarea name="item[' + counter + ']" rows="3" cols="90" maxlength="500"></textarea>';
var cell2 = row.insertCell(2);
cell2.innerHTML = '<input type="number" name="amount[' + counter + ']" style="width: 50px;"/>';
var cell3 = row.insertCell(3);
cell3.innerHTML = '<input type="checkbox" name="oneTime[' + counter + ']" value="1">';
var cell4 = row.insertCell(4);
cell4.innerHTML = '<input type="checkbox" name="supplier[' + counter + ']" value="1">';
var cell5 = row.insertCell(5);
cell5.innerHTML = '<a href="javascript:void(0)" onclick="deleteRow(' + counter + ')" class="deleteItemBoxButton btn btn-primary"><span class="glyphicon glyphicon-remove"></span></a>';
}
});
删除行后,所有行ID都变为相同的ID,而function deleteRow(rowid)
{
var row = document.getElementById(rowid);
var table = row.parentNode;
while (table && table.tagName != 'TABLE')
{
table = table.parentNode;
if (!table)
{
return;
}
table.deleteRow(row.rowIndex);
counter--;
}
var table = document.getElementById('rfqTable');
var trRows = table.getElementsByTagName('tr');
var tdRows = table.getElementsByTagName('td');
for (var i = 0; i < trRows.length; i++)
{
trRows[i].id = counter;
}
for (var i = 0; i < tdRows.length; i++)
{
document.getElementById("item").innerText = counter;
}
}
根本没有变化。
答案 0 :(得分:0)
在deleteRow函数中,为什么添加了这个 -
for (var i = 0; i < trRows.length; i++) {
trRows[i].id = counter;
}
您正在为所有行分配相同的值,因为您的计数器变量未更改。它应该是这样的 -
trRows[i].id = i + 1; // added + 1 since you want to start from 1 not 0
答案 1 :(得分:0)
th
为目标。所以现在删除一行后将重新排列ID,值总是从1开始。
var table = document.getElementById('rfqTable');
for (var i = 1; i < table.rows.length; i++)
{
var firstCol = table.rows[i].cells[0];
firstCol.innerText = i;
}