我有动态 html 表。当我按下添加按钮时。一个新行将附加到表中。每行都有一个取消按钮来删除自己。
问题出在删除和添加新行之后。编号不正确。 “文本列”中的值也不正确(顺序不正确)。
这是我的脚本:
html:
<input type="button" value="Add" id="btn_add" style="font-weight:bold" /><br />
<table id="t_output" border="1">
<tr class="info">
<td><strong>No</strong></td>
<td><strong>Text</strong></td>
<td><strong>Action</strong></td>
</tr>
</table>
jQuery:
$("#btn_add").click(function() {
var rowCount = $("#t_output tbody tr").length;
c_no = "<td>" + rowCount + " </td>";
c_txt = "<td>TEXT" + (999 - rowCount) + "</td>";
c_act = "<td align = 'middle'><input type='button' value='Cancel' id='del_btn' class='btn btn-danger' /></td>";
t_rows = "<tr>" + c_no + c_txt + c_act + "</tr>";
$("#t_output tbody").append(t_rows);
});
$('#t_output').on('click', '#del_btn', function() {
$(this).closest('tr').remove();
})
和一把 fiddle :https://jsfiddle.net/9fujvb21/
如果可能的话,我不希望对代码进行过多更改。谢谢你的帮助
最佳答案
这是一种方法:
function reCalculate() {
$('#t_output tr:not(.info)>td:first-child').each(function(i) {
$(this).text(i+1);
});
}
我编写此函数是为了计算在调用时为所有行分配新数字。现在,每当我们需要重新计算并为行分配数字时,我们只需调用此函数即可。
这是更新的 fiddle .
更新
function reCalculate() {
$('#t_output tr:not(.info)').each(function(i) {
$(this).find('td:first-child').text(i+1).next().text('TEXT'+(999-i));
});
}
这是更新的 fiddle .
关于javascript - 固定动态表中的编号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37648652/