简体   繁体   English

使用jQuery和CSS选择元素范围

[英]Selecting range of elements with jQuery and CSS

I am trying to select a range of anchor elements using nth-child pseudo selector. 我正在尝试使用nth-child伪选择器选择一系列锚元素。 The problem is that nth-child will work only with child elements, but I have a structure like this: 问题在于nth-child仅适用于子元素,但是我有一个这样的结构:

<div>
  <a>first link>
</div>
<div>
  <a>Second link</a>
</div>
<div>
  <a>Third link</a>
</div>

In this case, the following selector that I found useful for selecting first 2 matched elements doesn't work: 在这种情况下,我发现以下对选择前两个匹配元素有用的选择器不起作用:

$("a:nth-child(n+1):nth-child(-n+2)")

I created an example here: http://jsfiddle.net/o6w5orom/ , in the first example all the elements are returned instead of first 2. In the second one works but only with direct children. 我在这里创建了一个示例: http : //jsfiddle.net/o6w5orom/ ,在第一个示例中,所有元素都被返回,而不是前两个元素。在第二个示例中,该元素有效,但仅具有直接子元素。

So, is there a way to construct CSS selector for jQuery that will basically return a range of elements, something like nth-child, but will work on matched elements of a jQuery object ? 因此,有没有一种方法可以构造用于jQuery的CSS选择器,该选择器将基本上返回一定范围的元素(如nth-child),但将对jQuery对象的匹配元素起作用? I want to construct the selector, don't wan't to write logic to process a jQuery object. 我想构造选择器,不要编写逻辑来处理jQuery对象。

Use: $("div:nth-child(n+1):nth-child(-n+2) a") 用法: $("div:nth-child(n+1):nth-child(-n+2) a")

Select the divs with the nth-child then descend to the a 's 选择nth-child的div,然后下降到a

Yes, you are right - :nth-child returns only direct children. 是的,您是对的-:nth-​​child仅返回直系子代。 But what's the problem? 但是有什么问题呢? Use find. 使用查找。

$("div:nth-child(n+1):nth-child(-n+2)").find('a')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM