Javascript jQuery 第一个类型选择器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8531189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery first of type selector?
提问by Web_Designer
How would I select the first <p>
element in the following <div>
with jQuery?
我将如何使用 jQuery选择以下第一个<p>
元素<div>
?
<div>
<h1>heading</h1>
<p>How do I select this element with jQuery?</p>
<p>Another paragraph</p>
</div>
回答by James Allardice
Assuming you have a reference to the div
already:
假设您已经引用了div
:
$(yourDiv).find("p").eq(0);
If the first p
will always be a direct child of the div
, you could use children
instead of find
.
如果第一个p
始终是 的直接子代,则div
可以使用children
代替find
。
Some alternatives include:
一些替代方案包括:
$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
$(yourDiv).find("p:first");
$(yourDiv).find("p").first() //Just an alias for `.eq(0)`
Note that the eq
method will always be the fastest way to do this. Here's the results of a quick comparisonof the eq
method, :eq
selector and :first
selector (I didn't bother with the first
method since it's just an alias of eq(0)
):
请注意,该eq
方法将始终是执行此操作的最快方法。这里有一个结果快速比较的的eq
方法,:eq
选择和:first
选择(我没有打扰first
的方法,因为它只是一个别名eq(0)
):
回答by rkw
$('div p:first')
answer was too short to post without this useless sentence.
没有这个无用的句子,答案太短了。
EditThis is definitely a slow option. After looking at Jame's speed test, it looks like jQuery selectors work best when they piggy back off of css selectors.
编辑这绝对是一个缓慢的选择。在查看了 Jame 的速度测试之后,看起来 jQuery 选择器在搭载 css 选择器时效果最好。
回答by Colin
$("div p").first();
$("div p").first();
or $('div p:first');
或 $('div p:first');
Reference: http://api.jquery.com/first/
参考:http: //api.jquery.com/first/
Keep in mind that first() matches only a single element, the :first-child selector can match more than one: one for each parent.
请记住 first() 只匹配一个元素, :first-child 选择器可以匹配多个:每个父元素一个。
回答by Devner
You almost know the answer (from your post title). There is a selector in jQuery called :first-of-type
. Use it to find and add class to the first p tag automatically, like so:
你几乎知道答案(从你的帖子标题)。jQuery 中有一个选择器,名为:first-of-type
. 使用它自动查找类并将其添加到第一个 p 标签,如下所示:
$("div p:first-of-type").addClass('someClass');
回答by Devner
$('div p').first()
Should work. I think.
应该管用。我认为。
回答by Prabhakar Undurthi
This should work
这应该工作
$( "div p:first-of-type" ).css( "font-size: 10px" );
The above code finds the first paragraph in the div as @Denver pointed and changed its fonts-size
to 10px
上面的代码在@Denver 指向的 div 中找到第一段并将其更改fonts-size
为10px
Here is an example that explains even more about jQuery first-of-type selector
这是一个示例,它更详细地解释了jQuery first-of-type 选择器