如何在每次刷新页面时加载不同的图像? [英] How do I have a different image load on each page refresh?

查看:103
本文介绍了如何在每次刷新页面时加载不同的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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>

但我是一个jQuery和JavaScript newb,它不适合我。我肯定做错了什么,但我不知道从哪里开始使用jQuery。我很确定这是一个语法错误。有人可以帮帮我吗?

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?

谢谢!!

推荐答案

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

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

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

原始答案

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

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

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:

错误:

})(jQuery);

正确:

}(jQuery));

这篇关于如何在每次刷新页面时加载不同的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆