0

我正在使用 jQuery 制作照片库,我想要一个按钮来显示从相册中的照片中随机拍摄的照片。每次用户单击按钮时,此图片都应更改。我有这段代码,但每次按下按钮时,我都会让 div#images 充满图像,而不是每次都填满图像。

<script>
        $('button').on('click', function() {
            $.getJSON('images.json', function(data) {
                imageList = data;               
            });
            $('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;  
        });
</script>

如您所见,我从 JSON 文件中读取图像并从 1 随机化到文件的长度。任何的意见都将会有帮助。先感谢您。

4

3 回答 3

3

您需要在添加新图像之前清除图像 div,否则图像将继续添加。

  <script>
            $('button').on('click', function() {
                $.getJSON('images.json', function(data) {
                    imageList = data;  
                    //Also, move the code inside getJson(). getJson is asynchronous.
                    //Clear the images HTML
                    $('#images').empty();
                    $('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '>').;               
                });
            });
    </script>

只是想知道:为什么不通过 json 调用检索 1 个随机图像,而不是获取所有图像然后选择一个(在服务器上编写随机化代码)?

于 2012-10-16T18:32:40.993 回答
2

JSON 数据是否改变?否则,为什么每次都请求?没有必要将下面的randimagevar 分开,但以后可能很容易被其他人阅读。

$('button').on('click', function() {
    if ( typeof imageList == 'undefined' || !imageList.length )
    {
        $.getJSON('images.json', function(data) {
            imageList = data;
            var rand = Math.floor(Math.random() * imageList.length) + 1;
            var image = $('<img />').attr('src', imageList[ rand ].img_src );
            $('#images').html( image );
        });  
    }
    else
    {
       var rand = Math.floor(Math.random() * imageList.length) + 1;
       var image = $('<img />').attr('src', imageList[ rand ].img_src );
       $('#images').html( image );
    }
});
于 2012-10-16T18:40:33.837 回答
0

确保关闭图像标签并清除现有图像

<script>
    $('button').on('click', function() {
        $.getJSON('images.json', function(data) {
            imageList = data;               
        });
        $('#images').html("");
        $('#images').append('<img src=' + imageList[Math.floor(Math.random() * imageList.length) + 1].img_src + '/>');  
    });
</script>
于 2012-10-16T18:34:29.127 回答