如何选择元素?

时间:2010-11-18 13:39:03

标签: javascript jquery

为什么这段代码不起作用? 还有另一种选择第一项的方法吗?

<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')

4 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

在每个循环中,$(this)是您正在寻找的对象。除非你在$(this)里面搜索某些东西,否则你不需要做任何进一步的选择。如果你试图突出第一个,你应该在每次调用之外进行,因为调用n次并没有多大意义。

答案 2 :(得分:1)

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

答案 3 :(得分: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>
相关问题