Javascript 使用jQuery获取表格的最后一行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10731501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the last row of a table using jQuery?
提问by Rosh
I'm dynamically creating table rows. So each time I add a row, I need to get the ID of the last <tr>
so that I can create a new <tr>
with ID = "(the last row's ID) + 1"
. Is there any way to get the last row's ID using jQuery?
我正在动态创建表行。因此,每次添加一行时,我都需要获取最后一行的 ID,<tr>
以便我可以<tr>
使用ID = "(the last row's ID) + 1"
. 有没有办法使用jQuery获取最后一行的ID?
回答by coolguy
$('#yourtableid tr:last').attr('id');
回答by undefined
var id = $('table tr:last').attr('id');
回答by cmartin
Old question, but here's a different way using JQuery traversal which is a bit quicker:
老问题,但这是使用 JQuery 遍历的另一种方式,它更快一点:
$("#TableId").find("tr").last();
An alternative method to ID your rows, if they are all sequential is just to get the number of rows + 1.
如果行数都是连续的,则另一种 ID 行的方法是获取行数 + 1。
$("#TableId").find("tr").length + 1
回答by evilReiko
2019
2019年
As of jQuery 3.4.0 :last
is deprecated, use .last() instead, like this:
由于 jQuery 3.4.0:last
已弃用,请使用 .last() 代替,如下所示:
var id = $('#mytable tr').last().attr('id');
回答by Sharma Vikram
var tid=$('#tableid tr:last').attr('id');
alert(tid);
回答by Patrick Mutwiri
There are two methods and they both work $('#tableid tr:last')
and $('#tableid tr').last()
有两种方法,它们都有效$('#tableid tr:last')
并且$('#tableid tr').last()
回答by Ashif Shereef
You don't need to use jQuery for that. You can handle it in CSS counters. The counters automatically increments the index values and it also handles the rearrangement of numbers in case a row is deleted from the midst. The CSS counters can be implemented as follows. Insert it into your CSS file that take care of the styles of the HTML table.
您不需要为此使用 jQuery。您可以在 CSS 计数器中处理它。计数器会自动增加索引值,如果从中间删除一行,它还会处理数字的重新排列。CSS 计数器可以如下实现。将它插入到处理 HTML 表格样式的 CSS 文件中。
#yourtableid tbody
{
counter-reset: tablerow;
}
#yourtableid tbody .yourHTMLcellclass::before
{
counter-increment: tablerow;
content: counter(tablerow)". ";
}
回答by IMRUP
Last row id of table
表的最后一行 id
var lastid = $('table tr:last').attr('id');
var str = lastid .replace(/[^0-9]+/ig,"");