开发者

Select maxium 5 li items with jquery

开发者 https://www.devze.com 2023-02-05 17:22 出处:网络
I have a <ul> with a lot of <li> You can see this here: <ul> <li><img src=\"content/img/logos/pon.jpg\" alt=\"开发者_开发百科PON\" width=\"111\" height=\"63\" /></li&

I have a <ul> with a lot of <li> You can see this here:

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

But no my question. The li items have his own <img> tag. But i want make, that jquery show me 5 li items. How can i make with javascript / jquery. That he show me random 5 of this li items?

Thanks


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

Found in jQuery: select random elements.


As for the question posed by OP in the comments:

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)


When you are able to reference the li's, you'll be able to iterate it's children. Which are the li's. Example:

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

In the example above, you can reference to the li's with $(this). What you could do is store them in an array and fetch 5 randomly. You could do this using the Math.random method. Either rebuild the ul li list afterwards or remove the unwanted items with jQuery.


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

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

demo

0

精彩评论

暂无评论...
验证码 换一张
取 消