获取一行jQuery上的最后一个li

Get last li on a line jQuery

本文关键字:最后一个 li jQuery 一行 获取      更新时间:2023-09-26

我们有一个简单的ul

<ul>
   <li>some text</li>
   <li>some some text</li>
   <li>text more</li>
   <li>text here</li>
</ul>
ul { text-align: center; width: 100px; }
li { width: auto; display: inline; }

因此ul可以有多条线路。如何获取ul内每行的最后一个li

如果ul每行上的最后一个li是指每个ul中的最后li,则:

$('ul li:last-child');

然而,如果你的意思是,你的li在同一个ul中,写在源代码的几行上,现在你想在每行上得到最后一个,那么答案是你不能。DOM不关心代码中的换行符。


注意:正确的方法是给那些li提供一个单独的类。

<ul>
    <li></li><li></li><li class="last"></li>
    <li></li><li></li><li class="last"></li>
    <li></li><li></li><li class="last"></li>
</ul>

现在您可以使用CSS

li.last { color: #444 }

和jQuery

$('li.last');

正确的方式。。。

请参阅jquery.last((

$('ul li').last().css('background-color', 'red');

这将返回一组"ul每行上的最后一个li">

$("ul li:last");

要使用jQuery获取列表中的最后一项,只需使用last()方法即可。

有关详细信息,请参阅此处:http://api.jquery.com/last/

var item = $('#myList li').last()

使用:last选择器-http://api.jquery.com/last-selector/

$("ul li:last");

如果你想为多个ul找到最后一个li,试试这个:

var $lasts = $("ul").map(function(){
    return $(this).find("li:last");
});

工作示例:

http://jsfiddle.net/hunter/SBsqS/

var theList = document.getElementById('id_of_my_ul');
var theLastItem = theList.childNodes[theList.childNodes.length - 1];

不知道在JQuery中会怎么做,但它不可能是不同的

尝试使用:last选择器:http://api.jquery.com/last-selector