对动态表格行进行编号 [英] Numbering dynamic table rows
问题描述
我正在使用jQuery制作动态HTML表格。在表格中,我的用户有两个交互:
I'm working on making a dynamic HTML table using jQuery. In a table, my user has two interactions:
- 追加一行
- 删除特定行
对行编号的问题在于,如果用户删除特定行,那么该行后面的所有行都需要重新编号。我将不得不选择删除的行后面的所有行,并将它们的数字减1。
The problem with numbering the rows is that if a user removes a specific row, all of the rows following that row need to be renumbered. I would have to select all rows following the removed row and subtract their number by 1.
有没有更好的方法去解决这个问题?
Is there a better way to go about this?
编辑:下面是一个展示问题的JSFiddle: http://jsfiddle.net/LNXae / 2 /
Here's a JSFiddle demonstrating the problem: http://jsfiddle.net/LNXae/2/
我知道有序列表会自动对我的行重新编号,但我宁愿使用一个表,因为示例I'
I'm aware that an ordered-list would automatically renumber my rows, but I'd rather use a table since the example I'm giving now is pretty boiled-down.
推荐答案
http://jsfiddle.net/mblase75/LNXae/1/
首先,将计数器编号包裹在 $ b
First, wrap the counter number in a <span>
with a class for easy finding later:
$new_row.children('td').prepend('Row #<span class="num">' + ($new_row.index() + 1) + "</span>");
然后使用 .each
循环后,您删除所需的行。传递给 .each
的回调函数的第一个参数是一个从零开始的索引号,第二个参数是HTML元素:
Then update all these spans with an .each
loop after you remove the desired row. The first argument passed into .each
's callback function is a zero-based index number, and the second is the HTML element:
var $row = $(this).closest('tr'),
$table = $row.closest('table');
$row.remove();
$table.find('tr').each(function(i, v) {
$(v).find('span.num').text(i + 1);
});
这篇关于对动态表格行进行编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!