我正在构建一个简单的随机div显示器。
我想从“特色”ul中显示一个随机li,从“其他”ul中显示两个。见下文 -
<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>
我正在使用此代码作为第一个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>
和这个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 */
}
但我无法使用第二个选项。任何意见,将不胜感激。
答案 0 :(得分:0)
在jQuery :random filter的帮助下,您可以非常轻松地执行以下操作:
$('#featured > li, #others > li').hide();
$('#featured > li:random').show();
var i = 2;
while (i--) $('#others > li:hidden:random').show();