jquery - 元素的可行性[属性] :nth-of-type(n) selector

标签 jquery css jquery-selectors css-selectors

这个问题与选择器的工作方式有关,不是我遇到的问题。我正在处理一些与此类似的 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并注意到这句话说

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) 返回 undefined 是有道理的,因为第一个 textarea 没有 for 属性.

我的问题是,将来 element[attribute]:nth-of-type(n) 选择器是否有可能返回具有指定属性的第 n 个元素?由于 jQuery/CSS 的工作方式,这是否需要一个全新的选择器?

最佳答案

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 或类似内容中反射(reflect)的元素自身特征之外的其他标准。

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 和一个这样的文本区域,否则您可能需要使用 .each() 迭代 .example 元素(感谢 unintuitive 这些非标准选择器的方式)。

关于jquery - 元素的可行性[属性] :nth-of-type(n) selector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34499264/

相关文章:

javascript - 通过检查旧的 json 值来保留 JSON,同时添加动态键和动态值

jquery - DIV 位置固定,内部内容重叠

javascript - 根据表单的选择显示/隐藏标记不做任何事情

javascript - .setAttribute 在 for 循环中不起作用 - JavaScript

jquery - 获取动态表行(TR)html

javascript - jQuery 选择器在修改 DOM 后不起作用

jquery - 如何防止 jQuery 悬停事件在未完成时触发?

javascript - 使用 jQueryeach 循环访问 API

javascript - 根据屏幕分辨率自动调整网页大小

php - 如何在单个div中显示两行div