2011-01-21 73 views
1

最大信號5裏的項目我有一個<ul>了很多<li>你可以在這裏看到:選擇使用jQuery

<ul> 
         <li><img src="content/img/logos/pon.jpg" alt="PON" width="111" height="63" /></li> 
         <li><img src="content/img/logos/spo.png" alt="SPO Utrecht" width="130" height="67" /></li> 
         <li><img src="content/img/logos/campus.jpg" alt="Onderwijs Campus" width="137" height="86" /></li> 
         <li><img src="content/img/logos/cpwb.png" alt="CPWB" width="112" height="99"/></li> 
         <li><img src="content/img/logos/expertis.jpg" alt="Expertis" width="120" height="56" /></li> 
         <li><img src="content/img/logos/inos.jpg" alt="Inos" width="211" height="67" /></li> 
         <li><img src="content/img/logos/OSG.jpg" alt="OSG" width="130" height="51" /></li> 
         <li><img src="content/img/logos/pio.png" alt="Pio" width="138" height="92" /></li> 
         <li><img src="content/img/logos/Signum.png" alt="Signum" width="181" height="68" /></li> 
         <li><img src="content/img/logos/vgs.png" alt="VGS" width="192" height="63" /></li> 
        </ul> 

但是,沒有我的問題。李項目有他自己的<img>標籤。但我想讓jQuery向我展示5件物品。我怎樣才能使用JavaScript/jQuery。他向我展示了這個李項目的隨機5個?

感謝

回答

3
randomElements = jQuery("li").get().sort(function(){ 
    return Math.round(Math.random())-0.5 
}).slice(0,5) 

jQuery: select random elements找到。


至於由OP在評論中提出的問題:

var $allLi = $('ul li'), // All 
    showRandom = function() { 
     $allLi.hide().sort(function() { // Hide all, then sort 
      return Math.round(Math.random()) - 0.5; 
     }).slice(0, 5).show(); // Show first five after randomizing 
    }; 

showRandom(); // Do it now ... 
setInterval(showRandom, 1500); // ... and every 1.5 sec 

Demo

+0

你可以刪除`獲得()`如果你想`jQuery`對象回來了,不是的`DOMElement`的收藏品。 [演示](http://jsfiddle.net/jensgram/6qY37/) – jensgram 2011-01-21 07:56:14

0

當你能夠引用李時珍,你就可以遍歷它的孩子。這是李的。 實施例:

$('li').each(function(index) { 
    alert(index + ': ' + $(this).text()); 
    }); 

在上面的例子,可以參考裏與$(本)。 你可以做的是將它們存儲在一個數組中並隨機取5。你可以使用Math.random方法來做到這一點。之後重建ul li列表或使用jQuery刪除不需要的項目。

0
var li = $('ul li'); 
var len =li.length; 

while($('ul li:visible').length > 5) { 
    li.eq(parseInt(len * Math.random())).hide(); 
} 

demo