Jquery Get last row of table within last element i

2020-07-10 10:01发布

问题:

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.

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

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

回答1:

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

or:

$('#first tr:last')

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



回答2:

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.



回答3:

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


回答4:

.find():

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

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

or more simply in this case:

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

EXAMPLE



回答5:

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

$('#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