开发者

Jquery 2 random lists displaying side by side

I'm building a simple random div displayer.

I want to display one random li from the "featured" ul and two from the "others" ul. see below -

<ul id="featured">
I want to display one from this list
<li>Cat</li>
<li>Dog</li>
</ul>

<p>

<p>
<ul id ="others">
I want to display two from this list
<li>bird</li>
<li>monkey</li>
<li>Otter</li>
<li>Honey badger ( most awesome animal )</li>
</ul>
</p>

I'm using this code for the first ul -

<script type="text/javascript">

this.randomtip = function(){
    var length = $("#featured li").length; // this is where we put the id of the list
    var ran = Math.floor(Math.random()*length) + 1;
  开发者_运维知识库  $("#featured li:nth-child(" + ran + ")").show();
};

$(document).ready(function(){   
    randomtip();
});

</script>

and this CSS

#featured, #featured li{
    margin:0;
    padding:0;
    list-style:none;
    }
#featured{
    width:250px;
    font-size:16px;
    line-height:120%;
    float:left;
    }
#featured li{
    padding:20px;
    width: 500px;
    display:none; /* hide the items at first only to display one with javascript */
    }

But I can't get it to work with the second option. any advice would be appreciated.


With the help of jQuery :random filter you can do the following very easily:

jQuery

$('#featured > li, #others > li').hide();
$('#featured > li:random').show();

var i = 2;
while (i--) $('#others > li:hidden:random').show();    

Fiddle: http://jsfiddle.net/Y7cLr/2

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜