javascript 如何在单个表达式中编写具有多个 :eq 的 jQuery 选择器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8449449/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:29:06  来源:igfitidea点击:

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

javascriptjquerybrowser

提问by thiesdiggity

I have a quick question. How do I write a jQuery selector expression with multiple :eq() selectors? I want to go down the DOM tree but every hope isn't uniform. Here is what I have that works:

我有一个快速的问题。如何编写带有多个 :eq() 选择器的 jQuery 选择器表达式?我想沿着 DOM 树向下走,但每个希望都不尽相同。这是我所拥有的:

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

But is the following does not work:

但是以下不起作用:

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

Is there a more elegant way to write it without all the "find"'s?

在没有所有“查找”的情况下,是否有更优雅的方式来编写它?

回答by mreyeros

I believe that you could do the following and it should return all dom elements that match:

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

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

You could then iterate over the results returned, hope this helps.

然后您可以迭代返回的结果,希望这会有所帮助。

回答by northamerican

Using an eachloop - elegant and not repetitive:

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

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

Last I checked, this technique performs best:

最后我检查过,这种技术效果最好:

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