2014-10-30 81 views
0

这是我的场景的示例代码。我有一些使用来自MYSQL表的PHP在容器div中加载的元素。如何选择div元素后的一些特定数量的div元素?

<div id="itemContainer"> 
    <div class="item"> 
     test 
    </div> 
    <div class="item"> 
     test 
    </div> 
    <div class="item"> 
     test 
    </div> 
    <div class="item"> 
     test 
    </div> 
    <div class="item"> 
     test 
    </div> 
    <div class="item"> 
     test 
    </div> 
</div> 

所以他们可能是10或12个项目,但我只需要4个项目一次显示。所以我试着选择第四项后的所有项目。我尝试的方式有一些问题,所以我需要你的帮助。

$(document).ready(function() { 
     var items = $('#weekly_best_selling').children('.itemContainer').length; 
     if (items > 6) { 
      $('#weekly_best_selling').children('.itemContainer').nextAll('.itemContainer').css("background-color", "red"); 
     } 
    }); 

http://jsfiddle.net/yasithao3/j2zyhmr3/

+0

你可以使用。每()[链接](http://api.jquery.com/jquery.each/) – chaos505 2014-10-30 07:46:25

回答

7

可以使用:gt选择器来靶向具有指数比一个作为它参数传递更大的元件。还请注意,:gt选择器具有基于0的索引。用途:

$('#itemContainer .item:gt(3)').hide();//hide items having index greater than 3 

Working Demo

+0

谢谢。这是行得通的。 – Yasitha 2014-10-30 07:50:43

+1

@Yasitha:很高兴帮助:) – 2014-10-30 07:52:48

1
$('.item:gt(3)').hide() 

使用jQuery的:gt()选择。

+0

谢谢。这是行得通的。 – Yasitha 2014-10-30 07:50:13