element[attribute]:nth-of-type(n) 选择器的可行性

Feasability of element[attribute]:nth-of-type(n) selector

这个问题与 select 或其他人的工作方式有关,这不是我遇到的问题。我正在使用一些类似于此的 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)') 用于 select 第一个具有 for 属性的文本区域。我一直不确定。我重读了 documentation 并注意到这行说

Selects all elements that are the nth child of their parent in relation to siblings with the same element name.

textarea[for]:nth-of-type(1) 未定义是有道理的,因为第一个文本区域没有 for 属性。

那么我的问题是,将来是否有可能 element[attribute]:nth-of-type(n) select 或 return 具有指定属性的第 n 个元素?这需要一个全新的 select 还是因为 jQuery/CSS 的工作方式?

nth-of-type 使用实际 DOM 中的索引,而不是过滤列表中的索引,因此 nth-of-type(1) 将首先找到您的 textarea <textarea>...</textarea> 但您通过 [=13= 过滤了它] ... nth-of-type(2)<textarea for="1">foo</textarea>

nth-of-type(3)<textarea for="2">bar</textarea> 等...

所以答案是否定的,你不能为此使用 nth-of-type

要获得第一个带有 "for" 的子文本区域,您可以使用 document.querySelector

var first = document.querySelector('.example > textarea[for]');
var first = document.querySelectorAll('.example > textarea[for]')[0];
//or jQuery
var first = $('.example > textarea[for]:eq(0)');

BTW nth-of-type 索引从 1 开始而不是从 0...

My question then is, would it be possible in the future for an element[attribute]:nth-of-type(n) selector to return the nth element with the specified attribute?

不完全是,因为 :nth-of-type() 中的 "type" 具有非常具体的含义,并且因为对于简单的选择器来说,根据除元素本身以外的任何其他条件来匹配元素并不是很直观DOM 或类似内容中反映的特征。

Would this require a whole new selector because of the way jQuery/CSS work?

是的,这就是 Selectors 4 引入 :nth-match() 的原因,它已成为现有 :nth-child() 的扩展,根据选择器参数仅考虑元素的子集。请参阅我对 this question 的回答。在你的情况下它将是

$('.example').children(':nth-child(1 of textarea[for])')

这仍然没有在任何地方实施;希望这会在新的一年有所改变。

由于这是 jQuery,您可以使用 :eq(0),但除非您只有一个这样的 .example 和一个这样的文本区域,否则您可能需要迭代 .example 元素使用 .each()(感谢 unintuitive 这些 non-standard 选择器)。

从我的角度来看,这不是限制,它对 patters.But 的实施足够好,但不适合您的情况(selecting 单节点),我们也根本不需要。

在你的情况下,你不需要使用 nth-type-of(n) 因为你是 selecting 单个节点而不是具有某种模式的集合,例如 (odd , even , 2n+1 )

对于您的情况,您可以尝试以下方法

 $('.example textarea[for]').first()

如果您中继有 select 节点集 nth-of-type(n) 的场景。是的,它会工作 w/o 任何问题。

$('.example textarea[for]:nth-of-type(2n)')  This selector is working well enough.

查看演示 > 运行 代码片段

$(document).ready(function() {
  setTimeout(function() {
    $('.example textarea[for]:nth-of-type(2n)').css('background-color', 'red');
  }, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<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>