javascript - 固定动态表中的编号

标签 javascript jquery html

我有动态 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/

相关文章:

javascript - 如何判断节点类型

javascript - 使用 jQuery 按日期顺序排列 <p> 元素

javascript - 将 cookie 设置为视频播放几秒后显示的 div?

html - 具有两列和文本区域的 Bootstrap 行填满页面

Mouseleave 事件上的 Javascript setTimeout

javascript - 添加具有特定 ID 的文档而不覆盖现有文档

javascript - 使用 JQuery 隐藏和显示多个 div 以及隐藏标题

javascript - 更改 jQuery 中 if else 语句的图标

jquery - 对象不支持属性或方法 'dialog'

javascript - 我如何确定在第一次加载时是否在 jQuery 中单击了某些内容?