Javascript jquery find 获取第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2173971/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:05:53  来源:igfitidea点击:

jquery find to get the first element

javascriptjquery

提问by nickf

I am writing $(this).closest('.comment').find('form').toggle('slow');and the problem is each of the forms in the child is being toggled. I would like only the first form to be toggled. the html is something like the below and this is the a link

我正在写作$(this).closest('.comment').find('form').toggle('slow');,问题是孩子中的每个表格都被切换了。我只想切换第一个表单。html 类似于下面的内容,这是一个链接

<div comment>
<a href>
<form>
</form>
    <a href>
    <div comment>
    <form>
    </form>
    </div>
</div>

回答by nickf

You can use either

你可以使用

$(this).closest('.comment').find('form').eq(0).toggle('slow');

or

或者

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

回答by Dhanasekar

Use :firstselector like below :

使用:first如下选择器:

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

回答by nikola

I use

我用

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

because it's the most explicit way to select a slice of a query and because it can be easily modified to match not the first element but the next, etc.

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

回答by Olivier Royo

using jquery simply use:

使用 jquery 只需使用:

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

回答by Developer

Use the below example for jquery find to get the first element

使用以下示例进行 jquery find 获取第一个元素

More filtring methods With Demo

更多过滤方法与Demo

$(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>

回答by Aleksandar

The simplest way to get the first result of findis with good old [index]operator:

获得第一个结果的最简单方法find是使用良好的旧[index]运算符:

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

Works like a charm!

奇迹般有效!