Showing random divs using Jquery

后端 未结 3 524
挽巷
挽巷 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

    This does what you need: http://www.jsfiddle.net/Yn2pn/1/

    $(document).ready(function() {
        $(".Image").hide();
    
        var elements = $(".Image");
        var elementCount = elements.size();
        var elementsToShow = 4;
        var alreadyChoosen = ",";
        var i = 0;
        while (i < elementsToShow) {
            var rand = Math.floor(Math.random() * elementCount);
            if (alreadyChoosen.indexOf("," + rand + ",") < 0) {
                alreadyChoosen += rand + ",";
                elements.eq(rand).show();
                ++i;
            }
        }
    });
    

提交回复
热议问题