jQuery查找获取第一个元素

44
我正在编写$(this).closest('.comment').find('form').toggle('slow');,问题是子级中的每个表单都被切换了。我只想切换第一个表单。HTML类似于以下内容,这是一个链接。
<div comment>
<a href>
<form>
</form>
    <a href>
    <div comment>
    <form>
    </form>
    </div>
</div>

6
你已经得到了一个好的答案,但下次请花时间查看文档。JQuery有相当完善的文档,如果你只是在寻找:first选择器,那么自己很容易找到它......http://docs.jquery.com/Main_Page - Tomas Aschan
我尝试了但没找到。我不擅长jquery,这是我第二次使用它。我只学了一些基础知识,已经花了一个小时在这上面,还有我的之前的问题。 - user34537
4
也许你没有在api.jquery.com上查找,而是在docs.jquery.com的旧文档中查找。我必须同意,由于旧文档的结构,像这样简单的API函数曾经很难找到。 - nikola
7个回答

68
你可以使用以下任一选项
$(this).closest('.comment').find('form').eq(0).toggle('slow');
或者
$(this).closest('.comment').find('form:first').toggle('slow');

第二个选项对我起作用了,我必须选择第一个div jQuery(this).closest('.divmodule').find('div:first').attr('class'); - charles
FYI,$('.foo:first')的速度比$('.foo').first()慢得多。http://jsperf.com/jquery-first-vs-first-vs-eq-0-vs-0/2 - Malcolm Dwyer
2
如果你真的关心性能,原生的 getElementsByTagName 会快得多:http://jsperf.com/jquery-first-vs-first-vs-eq-0-vs-0/16 - Kuba Holuj
2
这个方法是先遍历整棵树,然后选择第一个元素吗?还是在找到第一个元素后就停止了?我问这个问题是因为我正在处理一棵有数百个嵌套节点的树,但只想选择第一个匹配的元素。我想知道这种方法对于这种情况是否非常低效。 - Jesse Aldridge

14

使用如下代码::first选择器:

$(this).closest('.comment').find('form:first').toggle('slow');

8

使用jQuery,只需简单地使用:

    $( "form" ).first().toggle('slow');

5

我使用

$([selector]).slice(0, 1)

因为它是选择查询片段最明确的方式,而且它可以很容易地修改以匹配不是第一个元素而是下一个元素等。


1

获取find的第一个结果最简单的方法是使用老牌的[index]操作符:

$('.comment').find('form')[0];

运行得非常好!


0

你可以像这样使用

$(this).find('>.comment').find('>form').toggle('slow');

0

使用以下示例来使用jQuery find获取第一个元素

{{link1:更多带演示的过滤方法}}

$(document).ready(function(){
  $(".first").first().css("background-color", "green");
});
.first{
    padding: 15px;
    border: 12px solid #23384E;
    background: #28BAA2;
    margin-top: 10px;
}
<!DOCTYPE html>
<html>
<head>
<title>jQuery First Method Example By Tutsmake</title> 
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> 
</head>
<body>
 
<h1>This is first() method example</h1>
 
<div class="first">
  <p>A paragraph in a div.</p>
  <p>Another paragraph in a div.</p>
</div>
<br>
 
<div class="first">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
<br>
 
<div class="first">
  <p>A paragraph in another div.</p>
  <p>Another paragraph in another div.</p>
</div>
 
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接