使用jQuery只查找第一个类

Find only first class with jQuery

本文关键字:第一个 查找 jQuery 使用      更新时间:2023-09-26

在下面的标记中,我只想找到类为.hide的第一个元素,并通过单击.add a来更改其类。

但是我找不到班级。

<div class="field">default</div>
<div class="field hide">find this 1</div>
<div class="field hide">and then this 2</div>
<div class="field hide">and then this 3 </div>
<div class="field hide">and then this 4</div>
<div class="field add"><a>Add more</a></div>

以下是我正在尝试的:

$('.add a').click(function(e) {
    e.preventDefault();                     
    $(this).parent().siblings().find(".hide").removeClass("hide").addClass("show");
});

JSFiddle:http://jsfiddle.net/ok38wrnt/

使用索引为0的:eq选择器仅针对第一个元素:

$(this).parent().siblings(".hide:eq(0)")

工作演示

findsiblings()下是错误的,因为兄弟项是您想要的项。

使用filter代替:

然后,您可以将:first添加到.hide中以获得第一个匹配。

JSFiddle:http://jsfiddle.net/TrueBlueAussie/ok38wrnt/2/

$('.add a').click(function (e) {
    e.preventDefault();
    $(this).parent().siblings().filter(".hide:first").removeClass("hide").addClass("show");
});

缩短为:

http://jsfiddle.net/TrueBlueAussie/ok38wrnt/5/

 $(this).parent().siblings(".hide:first").removeClass("hide").addClass("show");

可能会使用toggleClass,假设您永远不会丢失这两个类(或者您最终会同时设置这两个)。

.hide元素是a元素的父元素的兄弟元素,因此应该将siblings()与选择器一起使用。您还需要使用:first来匹配第一个找到的元素。试试这个:

$('.add a').click(function(e) {
    e.preventDefault();
    $(this).parent().siblings('.hide:first').toggleClass("hide show");
});

更新的fiddle

Jquery还提供了first()方法。
$('.add a').click(function(e) {
    e.preventDefault();                     
          $('.hide').first().removeClass("hide").addClass("show");
});

Fiddle