选择第j个前面的兄弟姐妹? [英] Select Nth previous sibling in jQuery?
问题描述
我尝试设置我的jQuery选择器,但我不知道我需要如何写它。
我有一个无序的列表看起来像这样:
< ul>
< li>某事< / li>
< li>某事< / li>
< li>某事< / li>
< li>某事< / li>
< li class =last> something< / li>
< / ul>
现在我知道如果我想选择最后一个孩子, .last或ul.li:last,但是如果我想要从最后一秒,第三或第20秒?
您可以使用 eq
:
$('ul li')。eq(X);
其中X是您想要的元素的基于0的索引。您还可以使用选择器表单:
$('ul li:eq(X)');
您也可以使用 nth-child
:
$('ul li:nth-child(X)');
本文档介绍了 nth-child
和
eq
:
While:eq只有一个元素,这匹配多个:每个父索引一个。每个父项具有偶数,奇数或方程的倍数。指定的索引是单索引的,相比之下:eq()从零开始。
c> $('ul li')。eq(19); 您将获得查询的第20个匹配元素(因此,如果文档中有多个列表,你的所有第19个孩子,而 $('ul li:nth-child(20)');
会得到你个人的第20个匹配的列表元素<$ c
$ b
要做类似秒到末尾的操作,那么这样做的正确方法是:
var $ ul = $('#mylist> li');
pre>
var $ el = $ ul.eq($ ul.length-2);
但你应该检查一下,确保length-2不小于0.
I'm trying to set up my jQuery selector but I'm not exactly sure how I need to write it.
I've got a unordered list that looks something like this:
<ul> <li>something</li> <li>something</li> <li>something</li> <li>something</li> <li class="last">something</li> </ul>
Now I know if I want to select the last child I can do that by using either "ul li.last" or "ul.li:last" but say if I wanted the second from last, or third, or 20th? Now would I do that?
解决方案You use
eq
:$('ul li').eq(X);
Where X is a 0-based index of which element you want. You could also use the selector form:
$('ul li:eq(X)');
And you could also achieve a similar result by using
nth-child
:$('ul li:nth-child(X)');
The documentation has this to say about the difference between
nth-child
andeq
:While :eq(index) matches only a single element, this matches more than one: One for each parent with index. Multiple for each parent with even, odd, or equation. The specified index is one-indexed, in contrast to :eq() which starts at zero.
So by doing
$('ul li').eq(19);
you would get the single 20th matched element of the query (so if there is more than one list in the document this won't get you "all 19th children", while$('ul li:nth-child(20)');
would get you the individual 20th matched list element of each<ul>
in the document.EDIT:
To do something like "second to last", the sane way to do it would be like:
var $ul = $('#mylist > li'); var $el = $ul.eq($ul.length-2);
But you should probably do a check to make sure length-2 is not less than 0.
这篇关于选择第j个前面的兄弟姐妹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!