Javascript Jquery 获取系列中最后一个元素中表格的最后一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12786801/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:15:47  来源:igfitidea点击:

Jquery Get last row of table within last element in a series

javascriptjqueryhtmlajax

提问by apttap

I have a series of slides based off of sections:

我有一系列基于部分的幻灯片:

<div id="slides">
    <section id="first">
        <section>
            <table>
                <thead>
                </thead>
                <tbody>
                    <tr id="somethingUnique">
                    ...
                    </tr>
                </tbody>
            </table>
        </section>
        <section>
            <table>
                <thead>
                </thead>
                <tbody>
                    <tr id="somethingUnique">
                    ...
                    </tr>
                </tbody>
            </table>
        </section> 
       ...
    </section>
</div>

I need to select grab the ID of the last row from the table in the last section of #first section.

我需要在#first 部分的最后一部分中选择从表中获取最后一行的 ID。

I'm using the following Jquery, getting "undefined" back...any ideas?

我正在使用以下 Jquery,返回“未定义”......有什么想法吗?

    var lastListItem = $('#first:last-child table>tbody>tr:last').attr("id");
    alert(lastListItem);

回答by hunter

$('#first table:last tr:last')

or:

或者:

$('#first tr:last')


http://jsfiddle.net/hunter/QMzHH/

http://jsfiddle.net/hunter/QMzHH/

回答by Joe Johnson

var lastListItem = $("#first").find("section").last().find("tr").last().attr("id");

I prefer using [0].id instead of .attr("id") since its one less method call; however, if you're not positive that you'll always have a table in that DOM position, attr is safer.

我更喜欢使用 [0].id 而不是 .attr("id") 因为它少了一个方法调用;但是,如果您不确定在那个 DOM 位置总是有一个表,那么 attr 更安全。

回答by Chase

.find():

。找():

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

获取当前匹配元素集中每个元素的后代,由选择器、jQuery 对象或元素过滤。

?$("#first")?.find("tr:last").attr("id")

or more simply in this case:

或者更简单地在这种情况下:

$("#first tr:last").attr("id")

EXAMPLE

例子

回答by Juan Mendes

The other answers work but the problem with your attempt is the fact that :last-childhas to be applied to the child element (section), not the parent (#first). The following should work

其他答案有效,但您尝试的问题:last-child在于必须应用于子元素 ( section) 而不是父元素 ( )的事实 #first。以下应该工作

$('#first section:last-child table>tbody>tr:last').attr("id");

And could be simplified to

并且可以简化为

$('#first section:last-child tr:last-child').attr("id");

http://jsfiddle.net/e7mUD/1

http://jsfiddle.net/e7mUD/1

回答by Anoop

var lastListItem = $('#first section:last  table tr:last').attr("id");