使用Jquery检索列表中的某些div

使用Jquery检索列表中的某些div,jquery,list,html,toggle,Jquery,List,Html,Toggle,我的问题看起来很简单:假设我有一个共享同一类“myClass”的div列表。使用Jquery,我希望将$I-th first divs(其中I是一个任意整数)存储在一个变量中,以便一次性操作它们(添加类,切换到所有这些)。我该怎么做呢?试试这个: var i=6; $(".myClass").slice(0,i).each(function(){ //do whatever you want here. //`this` is a jQuery object of

我的问题看起来很简单:假设我有一个共享同一类“myClass”的div列表。使用Jquery,我希望将$I-th first divs(其中I是一个任意整数)存储在一个变量中,以便一次性操作它们(添加类,切换到所有这些)。我该怎么做呢?

试试这个:

var i=6;
$(".myClass").slice(0,i).each(function(){
       //do whatever you want here. 
       //`this` is a jQuery object of the div element. For example:
       $(this).addClass("newClass");
});
试试这个:

var i=6;
$(".myClass").slice(0,i).each(function(){
       //do whatever you want here. 
       //`this` is a jQuery object of the div element. For example:
       $(this).addClass("newClass");
});

如果要对多个元素执行操作,您有几个选项,假设
$(选择器)
返回一个有效的元素选择,并且
i
包含相关的数字:

// hides all divs greater than the `i`-th
$(selector + ':gt(' + i + ')').hide();
。 或:

显然,使用您需要的任何jQuery方法来代替
hide()

参考资料:


如果您想对多个元素执行操作,您有几个选项,假设
$(选择器)
返回一个有效的元素选择,并且
i
保存相关数字:

// hides all divs greater than the `i`-th
$(selector + ':gt(' + i + ')').hide();
。 或:

显然,使用您需要的任何jQuery方法来代替
hide()

参考资料:


$i-th first
?你是指列表中的每个
$i-th
元素吗?你能展示一些有代表性的HTML,并清楚地解释你想做什么/发生什么(以及响应什么事件)?假设i=10,我的意思是十个第一个div我试图使用push()创建一个div数组,但你检查我的答案似乎很复杂?
$i-th first
?你的意思是列表中的每个
$i-th
元素吗?你能展示一些有代表性的HTML,并清楚地解释你想做什么/发生什么(以及响应什么事件)?假设i=10,我的意思是第一个十个div我试图使用push()创建一个div数组,但看起来很复杂,你检查了我的答案吗?