简体   繁体   English

无法读取未定义JSON的属性“ 0”

[英]cannot read property '0' of undefined JSON

I'm trying to make an image slider that changes the image 'displayMain' every few seconds. 我正在尝试使图像滑块每隔几秒钟更改一次图像“ displayMain”。 My problem is that when I call the displayMain function in setInterval, I continuously get a 'cannot read property 0 of undefined' error. 我的问题是,当我在setInterval中调用displayMain函数时,我不断收到“无法读取未定义的属性0”错误。 Even when I use the hardcoded value of jsonData[i].name, I receive the same error. 即使当我使用jsonData [i] .name的硬编码值时,我也会收到相同的错误。 The value gets passed in displayThumbs just fine, however. 不过,在displayThumbs中传递值就可以了。 Does anyone know why I can't retain the values in displayMain but can do so in displayThumbs? 有谁知道为什么我不能在displayMain中保留值,但可以在displayThumbs中保留呢?

window.addEventListener('load', function () {
    var mainDiv = document.getElementById('main');
    var descDiv = document.getElementById('main-description');
    var gallery = document.querySelector('#main-img');
    var ul = document.querySelector('ul');
    var li;
    var i = 0;
    var displayThumbs;
    var thumbName;
    var current = 0;
    var images = [];

    function displayMain () {
        var data = images[i];
        gallery.src = 'img/' + data[0];
        descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
    }

    function displayThumbs () {
        for (i = 0; i < images.length; i += 1) {
            var data = jsonData[i].name.replace('.jpg', '_thumb.jpg');
            // thumbnails use dom to make img tag
            li = document.createElement('li');
            thumbs[i] = document.createElement('img');
            var createThumbNail = thumbs[i].src = 'img/' + data;
            thumbs[i].setAttribute('alt', data);
            thumbs[i].addEventListener('click', function() {
                alert(createThumbNail);
            });
            ul.appendChild(thumbs[i]);
        }
    }

    // success handler should be called
    var getImages = function () {
        // create the XHR object
        xhr = new XMLHttpRequest();
        // prepare the request
        xhr.addEventListener('readystatechange', function () {
            if (xhr.readyState === 4 && xhr.status == 200) {
                // good request ...
                jsonData = JSON.parse(xhr.responseText);
                for (var i = 0; i < jsonData.length; i += 1) {
                    var data = [];
                    data.push(jsonData[i].name);
                    data.push(jsonData[i].description);
                    images.push(data);
                }

                displayMain();
                displayThumbs();
                setInterval(displayMain, 1000);
            }
            else {
                // error
            }    
        });

        xhr.open('GET', 'data/imagedata.json', true);
        xhr.send(null);    
    };

    // setInterval(getImages, 2000);
    getImages();
    // displayThumbs();
});

Your problem is that your displayMain uses whatever value i is at the time, and i never gets incremented, so it'll be equal to images.length after the for loop in displayThumbs . 您的问题是您的displayMain当时使用的是i所使用的任何值,并且i永远不会递增,因此在displayThumbs for循环之后它将等于images.length。 displayThumbs increments it itself, so you won't ever go beyond the end of the array. displayThumbs本身会对其进行递增,因此您永远不会超出数组的末尾。

In your comment, you mentioned that you want to cycle through the images. 在您的评论中,您提到要循环浏览图像。 This should work a bit better: 这应该工作得更好:

function displayMain () {
    var data;

    // wrap around to the first image
    if (i >= images.length) {
        i = 0;
    }

    data = images[i];
    gallery.src = 'img/' + data[0];
    descDiv.innerHTML = '<h2>' + data[1] + '</h2>';
    i++;
}

Personally, I would use a private i , just in case another function reuses the same variable: 就个人而言,我将使用私有i ,以防其他函数重复使用相同的变量:

function displayMain () {
    var data;

    // wrap around to the first image
    if (displayMain.i >= images.length || isNaN(displayMain.i)) {
        displayMain.i = 0;
    }

    data = images[displayMain.i];
    gallery.src = 'img/' + data[0];
    descDiv.innerHTML = '<h2>' + data[1] + '</h2>';

    // move to the next image
    displayMain.i++;
}

This attaches a variable named i to the function displayMain . 这会将名为i的变量附加到函数displayMain It will update this variable each time it is called, and no other function will use the same i variable. 它将在每次调用时更新此变量,并且没有其他函数将使用相同的i变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM