如何对每个循环中的第一个元素做一些不同的事情?

How to do something different with first element in each loop?

在 each() 循环中,是否可以对第一个元素而不是下一个元素进行处理?像这样:

$( '.selector').each(function(){
    // if first element found, do something
});

作为变体,像这样

$( '.selector').each(function(index, element) {
   if (index === 0) {
      // if first element found, do something
   }
});

或使用

$( '.selector:first')

Example

可能效率不高,但很简单:

$( '.selector').each(function(index){
  if (index === 0) {
    // first element found, do something
  }
});

您可以通过检查索引来确定它是否是第一个元素。

$('.selector').each(function(i, el) {
    if (i === 0) {
       // first element.. use $(this)
    }
});

或者,您也可以使用 .first() method:

访问循环 外部 的第一个元素
$('.selector').first();

:first selector 也可以:

$('.selector:first');
$('.selector').each(function(i, el){
    if ( i === 0) {
       // Will be done to first element.
    }

});