如何使用 jQuery 在“ul”中找到最后一个“li”?

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

How can I find the last "li" in a "ul" using jQuery?

jquery

提问by A.T.

I want to check the lithat is the last liin ul. How can I check that using jQuery?

我要检查的li是最后一个liul。如何使用 jQuery 检查?

<ul id="ulscroller">
    <li value="1" class="selected">1</li>
    <li value="2">2</li>
    <li value="3">3</li>
    <li value="4">4</li>
    <li value="5">5</li>
    <li value="6">6</li>
    <li value="7">7</li>
    <li value="8">8</li>
    <li value="9">9</li>
    <li value="10">10</li>
    <li value="11">11</li>
    <li value="12">12</li>
    <li value="13">13</li>
    <li value="14">14</li>
    <li value="15">15</li>
    <li value="16">16</li>
    <li value="17">17</li>
    <li value="18">18</li>
    <li value="19">19</li>
    <li value="20">20</li>
</ul>

回答by Denys Séguret

Just use the :last-childselector :

只需使用:last-child选择器:

$('#ulscroller li:last-child')

DEMO: http://jsfiddle.net/f5v6R/

演示:http: //jsfiddle.net/f5v6R/

For example, if you want to know if it has the selectedclass you may do

例如,如果你想知道它是否有selected你可以做的类

if ($('#ulscroller li:last-child').hasClass('selected')) {
   // do something
}

回答by Sushanth --

You can use the .last()matcher

您可以使用.last()匹配器

$('#ulscroller li').last()

回答by Codegiant

try this

尝试这个

$(function(){
    alert($('#ulscroller li:last-child').val());
})

回答by Nix

$('ul#ulscroller').children('li').last();

http://api.jquery.com/last/

http://api.jquery.com/last/

You could also do it like so:

你也可以这样做:

$('ul#ulscroller').children('li:last-child');

http://api.jquery.com/last-selector/

http://api.jquery.com/last-selector/

Here's an example to illustrate it: http://jsfiddle.net/TheNix/W92vF/

这里有一个例子来说明它:http: //jsfiddle.net/TheNix/W92vF/

回答by Wolf

Just use the following

只需使用以下

if($('#ulscroller li:last-child')[0] == liTocheck)
{
   alert("This is the last li");
}

Or

或者

if($('#ulscroller li').last()[0] == liTocheck)
{
   alert("This is the last li");
}

Here liTocheckis the li that needs to be compared

liTocheck是需要比较的li