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>

疑問に思うだけです。すべての画像を取得してから1つを選択するのではなく、json呼び出しを介して1つのランダムな画像を取得してみませんか(サーバーでランダム化コードを記述してください)。

于 2012-10-16T18:32:40.993 に答える
2

JSONデータは変更されますか?そうでなければ、なぜ毎回リクエストするのですか?rand以下のと変数を分離するimage必要はありませんが、後で他の人が読みやすい場合があります。

$('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 に答える