jQuery第一个类型选择器? [英] jQuery first of type selector?

查看:81
本文介绍了jQuery第一个类型选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用jQuery在以下< div> 中选择第一个< p> 元素?

How would I select the first <p> element in the following <div> with jQuery?

<div>
    <h1>heading</h1>
    <p>How do I select this element with jQuery?</p>
    <p>Another paragraph</p>
</div>


推荐答案

假设您有<$ c $的引用c> div 已经:

$(yourDiv).find("p").eq(0);

如果第一个 p 将始终是 div 的直接子项,您可以使用 children 而不是 find

If the first p will always be a direct child of the div, you could use children instead of find.

一些替代方案包括:

$(yourDiv).find("p:eq(0)"); //Slower than the `.eq` method
$(yourDiv).find("p:first"); 
$(yourDiv).find("p").first() //Just an alias for `.eq(0)`

的别名

请注意, eq 方法始终是执行此操作的最快方法。以下是 eq 快速比较的结果c $ c>方法,:eq 选择器和:第一个选择器(我没有打扰第一个方法,因为它只是 eq(0)的别名:

Note that the eq method will always be the fastest way to do this. Here's the results of a quick comparison of 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)):

这篇关于jQuery第一个类型选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆