在 jquery 中只选择一个类

Select only one single class in jquery

本文关键字:一个 jquery 选择      更新时间:2023-09-26

说我有多个类名为item。

<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

但我只想展示一个,顺序并不重要。我该怎么做?

$('.item').show() // this will show all of them

可以使用以下任一方法从匹配的集合中选择特定元素:

// show the first .item only  
$('.item:first').show();
$('.item').first().show();
// show the last .item only
$('.item:last').show();
$('.item').last().show();
// show the second .item only
$('.item:eq(1)').show();
$('.item').eq(1).show();

请注意,eq采用一个参数,该参数是要定位的元素的索引。

$('.item').eq(0).show() // it will display first item