2014-10-30 71 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