jQuery技术:在加载时随机化子元素

我想用javascript随机化任何

    的子元素。 我正在寻找最佳方法。 有人可以帮忙吗?

    假设我有一个带有5个

  • 元素的
      。 在加载时,我希望

    • 元素以随机顺序出现。

        快点出我的脑袋:

        另请看一下这个问题: 随机化div元素

        这就是我做的方式(JSFiddle示例: http : //jsfiddle.net/LNvqr/2/ )

        如果您使用jQuery并且具有与此类似的HTML:

         
        • one
        • two
        • three
        • four
        • five

        然后你可以简单地使用.detach来删除和存储

      • 元素的数组。
        接下来,使用数组的副本,使用Math.random()生成一个0到1之间的(伪)随机整数,该整数小于数组的大小。 将此作为随机索引从原始(有序)列表复制到新(随机排序)列表中。
        在每次迭代中从原始数组中删除随机选择的元素,并选择一个新的随机元素,直到重新插入所有元素:

         function shuffleList() { var origList = $("#rndList li").detach(); var newList = origList.clone(); for (var i = 0; i < newList.length; i++) { //select a random index; the number range will decrease by 1 on each iteration var randomIndex = randomInt(newList.length - i); //place the randomly-chosen element into our copy and remove from the original: newList[i] = origList.splice(randomIndex, 1); //place the element back into into the HTML $("#rndList").append(newList[i]); } } function randomInt(maxNum) { //returns a random integer from 0 to maxNum-1 return Math.floor(Math.random() * maxNum); } 

    您可以使用以下代码实现此目的:

     $(function () { var parent = $("#parent-container"); var divs = parent.children(); while (divs.length) { parent.append(divs.splice(Math.floor(Math.random() * divs.length), 1)[0]); } }); 

      以上就是jQuery教程分享在加载时随机化子元素相关内容,想了解更多jQuery开发(异常处理)及jQuery教程关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/jquerytutorial/558488.html

      (0)
      上一篇 2021年1月26日
      下一篇 2021年1月26日

      精彩推荐