2010-11-18 112 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

希望我能爲避免。每個的兩次投票()! – 2010-11-18 13:57:53

相關問題