javascript 从对象中检索数据仅在原始函数中有效

xsuvu9jc  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(117)

我在网站上使用JS从对象中检索数据时遇到问题。我让第三方抓取Instagram帖子并通过链接向我的网站提供JSON。我设法从链接中检索数据并对其进行操作,但当我尝试每5秒更改一次显示的图像时,问题就来了。
我采用了How to change an image every 5 seconds for example?的解决方案,并试图适应我的解决方案,但是,我得到了一个错误,其中posts[index]是未定义的,即使它不应该是。

posts = [];
let index = 0;

indexx = 0
$.getJSON('posts.json', function(data) {
    $.each(data, function(i, f) {
        posts[indexx] = f
        indexx = indexx + 1
    });
});

console.log(posts) // returns all the posts
 
window.onload = change();

function change() {

    console.log(posts) // Returns the list of posts
    console.log(posts[index]) // Returns 'undefined'
    console.log(posts[1]) // Returns 'undefined'
    
    $('#instaimg').attr('src', posts[index]["mediaUrl"])

    if (index == 5) {
        index = 0;
      } else {
        index++;
      }
    
      setTimeout(change, 5000);
}

我不知道我是否错过了什么,或者我缺乏JS知识是罪魁祸首,但如果有人能帮助它将不胜感激

qv7cva1a

qv7cva1a1#

您的代码存在以下几个问题:

  • 您的console.log(posts)将显示一个空数组,因为ajax回调尚未完成=>将其移动到.getJSON回调函数中
  • 每5秒递归调用一次change,例如调用堆栈将无限增长
  • 使用setInterval代替setTimeout
  • .getJSON回调函数中启动间隔计时器,以便在获取的数据就绪时启动
  • 使用.push()添加到数组,无需跟踪索引
  • 在执行任何操作之前,使用$(function() {确保DOM已准备就绪
  • 您使用硬编码长度4作为数据长度,请改为引用数组大小

更新代码:

let index = 0;
let posts = [];

$(function() {
  $.getJSON('posts.json', function(data) {
    //$.each(data, function(i, f) {
    //  posts.push(f);
    //});
    // It looks like data is the array you want to use, so:
    posts = data;
    setInterval(changeImage, 5000);
  });
});

function changeImage() {
  $('#instaimg').attr('src', posts[index++]["mediaUrl"]);
  if(index > posts.length) {
    index = 0;
  }
}

相关问题