jquery 选择器在最后

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

jquery selector before-last

jqueryjquery-selectors

提问by FFish

I have a dynamic list and need to select the before last item.

我有一个动态列表,需要选择最后一项。

<ul class="album">
    <li id='li-1'></li>
    <!-- ... -->
    <li id='li-8'></li>
    <li id='li-9'></li>
    <li class='drop-placeholder'>drag your favorites here</li>
</ul>

var lastLiId = $(".album li:last").attr("id"); // minus one?

回答by Nick Craver

You can use .eq()with a negative value (-1is last) to get nfrom the end, like this:

您可以使用.eq()负值(-1最后一个)n从末尾获取,如下所示:

$(".album li").eq(-2).attr("id"); // gets "li-9"

You can test it here.

你可以在这里测试

回答by richsage

Probably a neater way but how about:

可能是一种更简洁的方式,但如何:

var lastLiId = $(".album li:last").prev("li").attr("id");