JavaScript抛出'无法读取属性...未定义'错误

时间:2014-12-26 06:14:23

标签: javascript jquery

我正在尝试构建一个基本的JQuery应用程序,它从Flickr加载图像,将它们添加到一个jQuery对象数组中,依次将它们添加到DOM中,淡入它们,然后在3秒钟内将它们淡出。但是,在我的displayImage函数中,我不能使用.hide(),. fadeIn()或.fadeOut(),因为它会抛出'未捕获的TypeError:无法读取属性'fadeIn'of undefined'错误。这是我的代码,包括JS和HTML:

var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
//Creates the empty array of jQuery image objects
var images = [];
$.getJSON(url, function(flickrResponse){
    flickrResponse.items.forEach(function (photo){
        var $img = $("<img>").hide();

        $img.attr("src", photo.media.m);
        //Populates the images array with jQuery objects defined from the Flickr JSON request
        images.push($img);

        // $("main .photos").append($img);
        // $img.fadeIn();
    });
});

function displayImage(imgIndex) {
    var $displayedImg = images[imgIndex];
    $(".photos").fadeOut('slow');
    $(".photos").empty();
    $(".photos").append($displayedImg);
    $displayedImg.fadeIn('slow');
    //Function which recursively calls 'displayImage' every three seconds
    setTimeout(function(){
        imgIndex = imgIndex + 1;
        displayImage(imgIndex);
    }, 3000);
}
displayImage(0);
};

$(document).ready(main);

并且

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Flickr App</title>
  <link rel="stylesheet" type="text/css" href="stylesheets/styles.css">
</head>

<body>
  <header>

  </header>

  <main>
    <div class = "photos">
    </div>
  </main>


  <footer>
  </footer>

   <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
   <script src="js/app.js"></script>
 </body>

任何可能未定义的想法?请注意,var $img = $("<img>").hide();请求中的$.getJSON行不会抛出未定义的错误!

非常感谢!

编辑:

我还尝试创建一个同步请求来获取JSON,以确保在调用displayImage函数之前加载它,并且仍然会抛出相同的错误:

var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
var images = [];
//THIS IS WHAT HAS CHANGED
$.ajax({url: url,
        dataType: 'json',
        async: false,
        success: function(flickrResponse){
    flickrResponse.items.forEach(function (photo){
        var $img = $("<img>").hide();

        $img.attr("src", photo.media.m);

        images.push($img);

    });
}});

function displayImage(imgIndex) {
    var $displayedImg = images[imgIndex];
    $(".photos").fadeOut('slow');
    $(".photos").empty();
    $(".photos").append($displayedImg);
    $displayedImg.fadeIn('slow');

    setTimeout(function(){
        imgIndex = imgIndex + 1;
        displayImage(imgIndex);
    }, 3000);
}
displayImage(0);
};

$(document).ready(main);

1 个答案:

答案 0 :(得分:0)

在尝试displayImage(0)之前,您需要等待JSON返回。 JSON请求是异步的,因此在返回任何JSON之前,您正在调用displayImage

我建议逐步使用Javascript调试器来更好地了解正在发生的事情。您会看到images为空,因此$displayedImg未定义。

相关问题