[英]How can I get the next (x) number of children/siblings of a particular element in jQuery?
This is just an illustrative example, but say I had a list of divs containing elements: 这只是一个说明性示例,但是说我有一个包含元素的div列表:
<div>
<p></p>
<p></p>
<p></p>
</div>
<div>
<p></p>
<p></p>
<p></p>
</div>
<div>
<p></p>
<p></p>
<p></p>
</div>
My aim is to run a loop that goes through each div, gets the first 2 children and applies a particular CSS class to them. 我的目标是运行一个遍历每个div的循环,获取前两个孩子并将特定的CSS类应用于他们。
How would I go about achieving this? 我将如何实现这一目标?
Note that this might not necessarily be two elements, at a later date it may become the first ten elements (or more). 注意,这不一定是两个元素,以后它可能会成为前十个元素(或更多)。
$('div > :lt(2)').addClass(...);
:lt
选择器使用从零开始的索引。
Another option would be to do it this way: 另一种选择是采用这种方式:
$('div p').slice(0,2).css('color','red')
This is actually the preferred way because lt(2)
is not a native CSS selector so you lose some efficiency in the query. 实际上,这是首选方法,因为
lt(2)
不是本机CSS选择器,因此您在查询中会失去一些效率。
Because :lt() is a jQuery extension and not part of the CSS specification, queries using :lt() cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method.
因为:lt()是jQuery扩展,而不是CSS规范的一部分,所以使用:lt()的查询无法利用本机DOM querySelectorAll()方法提供的性能提升。
You can use the lt
jQuery selector 您可以使用
lt
jQuery选择器
$('div p:lt(2)').each(function(index, value) {
// do something with $(value)
});
You can call children() followed by slice() : 您可以先调用children(),再调用slice() :
var childCount = 2;
$("div").each(function() {
$(this).children().slice(0, childCount).addClass("yourClass");
});
You could try something like this with nested loops: 您可以尝试使用嵌套循环这样的操作:
var amt = 2;
$('div').each(function(){
$(this).children().each(function(index, item){
if(index == amt) return false;
$(this).addClass('something');
});
});
查看您的标记,您可以尝试选择第一个孩子
$('div > :lt(2)')
$('div').each(function(){
var c = $(this).children();
for(var i=0; i < 2 && i < c.length; i++)
$(c[i]).html(i);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.