Showing random divs using Jquery

后端 未结 3 523
挽巷
挽巷 2020-11-27 18:51

I have a list if divs which contain images. I need to randomly show 4 of these each time the page loads. Here\'s the code I\'m starting with.

3条回答
  •  抹茶落季
    2020-11-27 19:30

    jQuery(function($){
      var sortByN = function(a,b){ a=a.n; b=b.n; return ab?1:0 };
      $.each( $('div.Image').map(
        function(){ return { div:this, n:Math.random() }; }
      ).get().sort(sortByN), function(i){
        if (i<4) $(this.div).show();
      });
    });
    

    Note that this will always show the divs in the same order as the original. Is that acceptable?

提交回复
热议问题