2010-11-18 19 views
2

なぜこのコードは機能しませんか? また、最初のアイテムを選択する別の方法はありますか?私はこのような要素を選択することができます知っている要素の選択方法は?

<div> 
    <a href="#">text</a> 
    <a href="#">text</a> 
</div> 

<script type="text/javascript"> 
$(function() { 
    $('div a').each(function(){ 
      $(':first', this).css('color', 'red'); 
     //...other actions with $(this) 
    }); 
}); 
</script> 

:各ループ内$('div a:first')

答えて

1

多分これはあなたが

<div> 
    <a href="#">text</a> 
    <a href="#">text</a> 
</div> 

<script type="text/javascript"> 
    $(function() { 
     $('div a').each(function(i, elm){ 
      if (i == 0){ 
       $(elm).css('color', 'red'); 
      }        
      //...other actions with $(this) 
     }); 
    }); 
</script> 
1

を、$(この)あなたが探しているオブジェクトです。 $(this)の中で何かを探していない限り、それ以上の選択は必要ありません。最初のものを強調表示しようとしている場合、それをn回呼び出すことはあまり意味がないので、それぞれの呼び出しの外で行う必要があります。

1
$(function() { 
    $('div a').each(function(index){ 
      if(index === 0){ 
       $(this).css('color', 'red'); 
      } 
     //...other actions with $(this) 
    }); 
}); 
2

これらは機能します。

$('div a').first(); 
$('div a').eq(0); 
$('div a').slice(0,1); 
$('div a').filter(':first'); 

あなたが最初、無センスループをしたい場合。

何らかの目的で残りの部分が必要な場合は、セレクタの結果をキャッシュし、必要なものを取り出します。

var $div_a = $('div a'); 

$div_a.first(); // for the first 
$div_a.slice(1,4); // for the second through fourth 
+2

が)私は.each(の回避のために二回投票でき願いたいものです! –