【问题标题】:Jquery 2 random lists displaying side by sideJquery 2随机列表并排显示
【发布时间】:2011-08-26 11:38:32
【问题描述】:

我正在构建一个简单的随机 div 显示器。

我想显示来自“特色”ul 的一个随机 li 和来自“其他”ul 的两个随机 li。见下文-

<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 */
    }

但我无法让它与第二个选项一起使用。任何意见,将不胜感激。

【问题讨论】:

  • 那么什么不起作用?您移植的代码是否适用于第一个 UL?您是否有第二个功能不适用于第二个 UL?或者你想重用部分 div 的第一个函数?
  • 所以我尝试使用 -

标签: jquery math random


【解决方案1】:

jQuery :random filter 的帮助下,您可以非常轻松地做到以下几点:

jQuery

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

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

小提琴: http://jsfiddle.net/Y7cLr/2

【讨论】:

  • 谢谢加里!看起来在 Fiddle 上工作,但是当我尝试将它复制到我的本地 html 文件时它不会工作。我已经使用 google api 添加了 jquery 并为 javascript 和 css 输入了正确的脚本类型。我错过了什么吗?
  • 确保将代码放在$(document).ready(function() { /* [....] your code here [....] */ }); 中,这样它只会在准备就绪时作用于DOM 元素。还要确保你有那个 jQuery 随机过滤器插件。执行alert(jQuery); 以查看是否已加载 jQuery。
  • 缺少准备好的功能:-/。再次感谢您的回复!
猜你喜欢
  • 2014-05-21
  • 2017-01-19
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多