如何在每次刷新页面时加载不同的图像?

时间:2013-06-22 01:48:02

标签: jquery image page-refresh

我试图在每次页面刷新时有不同的图像加载。我试过这段代码:

<!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>

但我是一个jQuery和JavaScript新手,它对我不起作用。我肯定做错了什么,但我不知道从哪里开始使用jQuery。我很确定这是一个语法错误。谁能帮助我?

谢谢!

1 个答案:

答案 0 :(得分:1)

有些来回,但这里是代码,这应该没有问题:

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


原始答案

您的代码有效http://jsfiddle.net/AstDerek/AC6tu/

如果仍有问题,请尝试检查jQuery是否已加载。如果对匿名函数的调用是在括号的第一个匹配项之外进行的,则浏览器可能会抱怨:

错:

})(jQuery);

右:

}(jQuery));