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