在jQuery中,如何测试一个元素是否是同一类的多个元素中的第一个

In jQuery, how to test whether an element is the first of many elements of same class?

本文关键字:元素 一类 jQuery 第一个 是否是 何测试 测试 一个      更新时间:2023-09-26

我有3个div:

<div class='squares' id='div1'></div>
<div class='squares' id='div2'></div>
<div class='squares' id='div3'></div>

使用jQuery,我想将css属性(右边框)应用于除第一个之外的所有div。

我应该使用的if语句是什么?我想在if语句中使用类(而不是id)。

非常感谢。

您可以使用:not():first选择器:

$('.squares:not(:first)').addClass('border')

或:

$('.squares:not(:first)').css('border-right', 'value')

您使用:first:not()选择器绑定了吗?

我还没有测试,但下面的代码应该可以做你想做的:

$(".squares:not(:first)").css("border-right", "thin solid red");

if语句中使用.is()

if (!$(this).is(".squares:first()")) {
    // not the first square 
}