带有nth-of-type的jQuery选择器()
使用Chrome开发工具
jQuery('.proejct-text-field')
给我四个HTML元素实例:
... ... ... ...
尝试以下操作不会返回任何元素。
jQuery('.proejct-text-field:nth-of-type(1)')
至于我的理解,应该返回第一个元素。 我只是使用jQuery来为我的目的找到合适的选择器并将它们带入我的css文件中。 那么如何选择那些Div的第一个元素。 顺便说一句:它们没有包裹在某个父元素中。 所以任何子方法都行不通。 此外,div的数量是可变的。
你的class
名称不正确,你有一个.
在class=".proejct-text-field ..."
。
此外,您可以使用.first()
来选择第一个元素
$('.proejct-text-field').first();
你不能选择nth-of-class
因为没有这种方法可以选择带有class
nth
元素,所以你的选择器应该可以工作,但不是因为你必须取出句号.
来自DOM中的class
名*)
演示
演示2 (使用jQuery .first()
)
nth-of-type选择器查找元素类型,如div, span
等,而不是类名或任何其他选择器
使用:eq(索引)
jQuery('.proejct-text-field:eq(0)')
或.eq(索引)
jQuery('.proejct-text-field').eq(0)
首先改变这个标记
...<>
代替
...<>
如果你想先使用.first()
jQuery('div.proejct-txt-field').first();
:nth-of-type()
选择器 “选择与父节点相关的所有元素与具有相同元素名称的兄弟节点相关。” – 但是你指出你的元素“没有包裹在某个父元素中”,即它们彼此没有特别的关系。
如果您只想要该类的第一个元素,请执行以下操作:
jQuery('.proejct-text-field').first() // or jQuery('.proejct-text-field').eq(0) // or jQuery('.proejct-text-field:first') // or jQuery('.proejct-text-field:eq(0)')
请注意,您应该删除.
来自标记中class=""
属性的类名。 即,它应该是:
class="proejct-text-field"
(而且你到处拼错了“项目”。)
首先,你有一个.
在你的class级姓名中,这是不必要的……只需将其作为proejct
而不是nth-of-child
,使用:eq
,就像这样
和你的jQuery
jQuery('.proejct-text-field:eq(0)');
要么
jQuery('.proejct-txt-field').first();