-1

次のエラーが表示されます: TypeError: slides[i] is undefined.

slides 変数にアクセスできるべきではないので、それは奇妙ですか?

<script>
    $('document').ready(function() {
        $.ajax({
            type: "POST",
            url: "getSlides.php",
            data: '',
            cache: false,
            success: function(response)
            {
                var slides = JSON.parse(response);
                for (var i = 0; i < slides.length; i++) {
                    setTimeout(function() {
                        if (slides[i].type === 'image') {
                            $('#slideshow').html('<img src="' + slides[i].image_video + '" />');
                        }
                    }, 2000);
                }
            }
        });
    });
</script>
4

5 に答える 5

1

関数コールバック、refフィドルの例sildes[i]にプロキシできますsetTimeout

$('document').ready(function () {
    $.ajax({
        type: "POST",
        url: "getSlides.php",
        data: '',
        cache: false,
        success: function (response) {
            var slides = JSON.parse(response);
            for (var i = 0; i < slides.length; i++) {
                setTimeout(function (slide) {
                    if (slide.type === 'image') {
                        $('#slideshow').html('<img src="' + slide.image_video + '" />');
                    }
                }, 2000, slides[i]);
            }
        }
    });
});
于 2013-11-14T11:39:58.273 に答える
0

because due to setTimeOut it calls your code after 2000ms, on that time value of i is slides.length for which it throw the error.

You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.

 success: function (response) {
     var slides = JSON.parse(response);
     for (var i = 0; i < slides.length; i++) {
         doSetTimeout(slides, i);

     }
 }

 function doSetTimeout(slides, i) {
     setTimeout(function () {
         if (slides[i].type === 'image') {
             $('#slideshow').html('<img src="' + slides[i].image_video + '" />');
         }
     }, 2000);
 }
于 2013-11-14T11:41:42.877 に答える