如何编写一个jQuery选择器,在单个表达式中使用多个:eq's

How to write a jQuery selector with multiple :eq's in single expression?

本文关键字:表达式 eq 单个 何编写 一个 jQuery 选择器      更新时间:2023-09-26

我有一个简短的问题。我如何写一个jQuery选择器表达式与多个:eq()选择器?我想沿着DOM树往下走,但希望不尽相同。这是我的工作:

$('div:eq(0)').find('div:eq(1)').find('div:eq(5)')

$('div:eq(0) div:eq(1) div:eq(5)')

有没有更优雅的方式来写它,而不需要所有的"find"?

我相信您可以做以下操作,它应该返回所有匹配的dom元素:

 $('div:eq(0), div:eq(1), div:eq(5)')

您可以遍历返回的结果,希望这对您有所帮助。

使用each循环-优雅且不重复:

$.each([0, 1, 5], (_, n) => {
    $('div').eq(n);
});

最后我检查了一下,这种技术性能最好:

$('div').filter(':eq(0), :eq(1), :eq(5)');

如果你的索引是在一个数组中,并且你计划在你的集合上链方法:

var aIndexes = [1,6,17];
$collection.filter( function() {
   return aIndexes.indexOf($(this).index()) > -1;
} ).<chained methods on filtered collection>