Javascript jQuery重用选择器并操作项
我想选择某个类的所有元素,然后在页面运行时对它们进行操作。我不想不断地查询同一组项目,但我确实需要访问不同的元素。我的意思是:Javascript jQuery重用选择器并操作项,javascript,jquery,selection,Javascript,Jquery,Selection,我想选择某个类的所有元素,然后在页面运行时对它们进行操作。我不想不断地查询同一组项目,但我确实需要访问不同的元素。我的意思是: var items = $(".these"); // The items I need to use items.first().hide() // Hide the first item $(".these:nth-child(3)"); // How could I get the third element of items and perform jQuer
var items = $(".these"); // The items I need to use
items.first().hide() // Hide the first item
$(".these:nth-child(3)"); // How could I get the third element of items and perform jQuery functions on them without querying again?
items[3].hide() // Doesn't work because the third element isn't accessed with jQuery.
我需要能够用索引来实现这一点。例如,现在我正在做:
$(".these:nth-child(" + index + ")");
您只需要使用th eq()函数
类似的东西
var items = $('.these');
items.find(':nth-child(3)').hide();
我想您正在寻找jQuery中的
.filter()
函数。看见
e、 g
或者,如前所述,如果您只想追求某个指数,请使用eq。但是,筛选器可以接受任何jQuery选择器。例如
items.filter(':visible:first')
找到之前操作后仍然可见的第一个。搞定了!谢谢你这么简单的解决方案!有趣的注意事项-当使用第n个子元素时,第一个元素是元素1,但当使用eq()时,第一个元素是元素0。是的,jQuery将函数推荐给选择器。;-)这更像是:第n个类型。仅当父对象的子对象是同一选择器时,此选项才有效。我使用了eq()解决方案,效果非常好。你知道滤波器和均衡器的区别吗?当eq严格基于索引时,过滤器是否更宽泛,并允许您使用不同的过滤方式?几乎如此。我们为filterNo添加了另一个示例,它将在项的子元素中查找第三个子元素,而不是作为其父元素的第三个子元素的项。
items.filter(':visible:first')