How do I have a different image load on each page refresh?

情到浓时终转凉″ 提交于 2019-12-08 13:22:27

问题


I am trying to have a different image load with each page refresh. I have tried this code:

<!DOCTYPE html><html><body> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script><script type="text/javascript" src="jquery-source"></script> <script>$(document).load( ... )</script><script type="text/javascript">(function($){

$.randomImage = {
    defaults: {

        //you can change these defaults to your own preferences.
        path: 'http://mysite.com/images/', //change this to the path of your images
        myImages: ['Testimonial1.png', 'Testimonial2.png', 'Testimonial3.png', 'Testimonial4.png', 'Testimonial5.png' ] //put image names in this bracket. ex: 'harold.jpg', 'maude.jpg', 'etc'

    }           
}

$.fn.extend({
        randomImage:function(config) {

            var config = $.extend({}, $.randomImage.defaults, config); 

             return this.each(function() {

                    var imageNames = config.myImages;

                    //get size of array, randomize a number from this
                    // use this number as the array index

                    var imageNamesSize = imageNames.length;

                    var lotteryNumber = Math.floor(Math.random()*imageNamesSize);

                    var winnerImage = imageNames[lotteryNumber];

                    var fullPath = config.path + winnerImage;


                    //put this image into DOM at class of randomImage
                    // alt tag will be image filename.
                    $(this).attr( {
                                    src: fullPath,
                                    alt: winnerImage
                                });

            }); 
        }   
});

}(jQuery));</script>
</body>
</html>

But I am a jQuery and JavaScript newb, and it's not working for me. I'm definitely doing something wrong, but I don't know where to begin with jQuery. I'm pretty sure it's a syntax error. Could anyone help me out?

Thank you!!


回答1:


Some back and forth, but here is the code, this should work with no problems:

https://gist.github.com/AstDerek/5841966


Original answer

Your code works http://jsfiddle.net/AstDerek/AC6tu/

If you still have problems, try checking jQuery is loaded. The browser may complain if the call to the anonymous function is made outside of the first match of parenthesis:

Wrong:

})(jQuery);

Right:

}(jQuery));


来源:https://stackoverflow.com/questions/17246566/how-do-i-have-a-different-image-load-on-each-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!