使用jquery选择最多5个li项

时间:2011-01-21 07:36:05

标签: javascript jquery arrays select

我有<ul>有很多<li>你可以在这里看到:

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

但不是我的问题。 li项目有自己的<img>标记。但我想要制作,那个jquery给我看了5件物品。我怎样才能使用javascript / jquery。他随机向我展示了这些李物品中的5件?

由于

3 个答案:

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

答案 1 :(得分:0)

当你能够引用li时,你将能够迭代它的孩子。这是李的。 例如:

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

在上面的示例中,您可以使用$(this)引用li。 你可以做的是将它们存储在一个数组中并随机获取5。您可以使用Math.random方法执行此操作。之后重建ul li列表或使用jQuery删除不需要的项目。

答案 2 :(得分:0)

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

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

demo