Any way to shuffle content in multiple div elements

前端 未结 8 1129
鱼传尺愫
鱼传尺愫 2020-12-31 23:32

I\'m relatively new to Javascript and was wondering if there\'s a quick way to shuffle content that is contained in multiple

tags. For example

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 00:12

    Expanding on the nice answer by @gilly3, using jQuery one can actually avoid appending randomly-chosen elements of divs in a loop, by randomly sorting divinstead and appending them all at once:

    $(function() {
      var parent = $("#shuffle");
      var divs = parent.children();
      divs.sort(function(a, b) {
        return 0.5 - Math.random();
      });
      parent.append(divs);
    });
    

    Demo: http://jsfiddle.net/ey70Lxhk/

    Note however that this technique is not accurate in terms of randomness, and relies on sort which does not scale linearly with the number of elements.

提交回复
热议问题