【发布时间】:2016-04-02 15:24:14
【问题描述】:
这个问题与选择器的工作方式有关,不是我遇到的问题。我正在使用一些类似于此的 HTML:
<div class="example">
<textarea>...</textarea>
<textarea for="1">foo</textarea>
<textarea for="2">bar</textarea>
<textarea for="3">hello</textarea>
<textarea for="4">world</textarea>
</div>
我试图使用$('.example').children('textarea[for]:nth-of-type(1)') 选择具有for 属性的第一个文本区域。我一直不确定。我重读了documentation 并注意到那行说
选择与其父级的第 n 个子级相对于具有相同元素名称的兄弟级的所有元素。
textarea[for]:nth-of-type(1) 将返回 undefined 是有道理的,因为第一个 textarea 没有 for 属性。
那么我的问题是,element[attribute]:nth-of-type(n) 选择器将来是否有可能返回具有指定属性的第 n 个元素?由于 jQuery/CSS 的工作方式,这是否需要一个全新的选择器?
【问题讨论】:
-
“将来
element[attribute]:nth-of-type(n)选择器是否有可能返回具有指定属性的第 n 个元素” - 不,因为正如您已经指出的那样,那就是不是:nth-of-type()的工作方式。它基于元素的标签type。您可能已经知道这一点,但为了记录,您可以使用:eq()选择器或.eq()方法通过其索引基于匹配元素的集合 获取元素。在您的情况下,$('.example').children('textarea[for]:eq(0)')- 使用0的索引,因为eq是从零开始的,而:nth-of-type不是, -
@JoshCrozier 实际上我确实使用了
:eq()选择器。所以我猜想一个全新的选择器需要与属性选择器一起进行第 n 个类型的选择?
标签: jquery css jquery-selectors css-selectors