javascript - 随机div,只显示其中的一部分

标签 javascript jquery html

我在我的网站上使用此代码来随机化 div 的顺序。在我的一个子页面上,我想在稍作修改的版本中使用它 - 将再次以随机顺序显示 12 个 div,但只会显示前 3 个,其余将设置为“display:none;”或者用js实现类似的效果。

有什么建议可以修改下面的代码,以便只显示前 3 个 div 吗?

这是代码:http://jsfiddle.net/ca7WW/

HTML:

<div class="randomize">
    <div class="random_div">1</div>
    <div class="random_div">2</div>
    <div class="random_div">3</div>
    <div class="random_div">4</div>
    <div class="random_div">5</div>
    <div class="random_div">6</div>
    <div class="random_div">7</div>
    <div class="random_div">8</div>
    <div class="random_div">9</div>
    <div class="random_div">10</div>
    <div class="random_div">11</div>
    <div class="random_div">12</div>
</div>

jQuery:

function shuffle(array) {
  var currentIndex = array.length
    , temporaryValue
    , randomIndex
    ;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

(function ($) {
    $.fn.randomize = function (childElem) {
        return this.each(function () {
            var $this = $(this);
            var elems = shuffle($(childElem));
            $this.remove(childElem);
            for (var i = 0; i < elems.length; i++)
            $this.append(elems[i]);
        });
    }
})(jQuery)

jQuery(function($){
    $("div.randomize").randomize("div.random_div");
});

最佳答案

使用 :lt:gt 获取选择器中的“前 N 个”或“后 N 个”元素。

DEMO

jQuery(function($){
    $("div.randomize").randomize("div.random_div");
    $(".random_div:gt(2)").hide(); // This hides anything after the 3rd element
});

关于javascript - 随机div,只显示其中的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22253417/

相关文章:

jquery - 使用对象文字创建具有属性的元素

html - 对于伪元素,省略号在 Firefox 中无法正常工作

javascript - 使一个 DIV 扩展一个 View (即显示另一个 DIV)

javascript - Vue.js 选择具有特定类名的最接近的 div

JavaScript 检查资源是否可以通过 fetch 访问

javascript - 计算类中的特定字符(并将文本 chop 逻辑应用于该类的每个实例)

javascript - CSS 无法按 Angular 插值工作

javascript - jQuery getJSON 打印名称为字符串的数组

javascript - 如何从页面中临时删除 iframe,然后在不重新下载 iframe 内容的情况下重新添加 iframe?

javascript - 如何在按钮组中输出变量以影响 Angular.js 和 Html 中的下拉结果