【问题标题】:JavaScript loop through JSON data and print in htmlJavaScript 循环遍历 JSON 数据并在 html 中打印
【发布时间】:2019-09-12 02:52:00
【问题描述】:

我是 JavaScript 新手,我正在尝试找出如何循环遍历 JSON 并在 HTML 中打印每个选定的值。除了打印 JSON 数据的“所有”行之外,我下面的解决方案可以满足我的所有需求。它只打印最后一个。我一直在研究 StackOverflow 和其他地方,但我没有找到解决方案。对不起,如果这是一个多余的问题,感谢您的帮助!

    //Fetch JSON from URL
    //https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch('https://s.codetasty.com/toddbenrud/sandBoxToddBenrud/example/songData.json')
          .then(function(response) {
            return response.json();
          })
          .then(function(myJson) {
                var songData = (JSON.stringify(myJson));
                //https://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript 
                var index;
                var obj = JSON.parse(songData);
                for (index = 0; index < obj.length; ++index) {

                    var student_name = obj[index]['name'];
                    var student_email = obj[index]['email'];
                    var song_name = obj[index]['song'];
                    var song_url = obj[index]['url'];

                    document.getElementById("studentName").innerHTML = '<br>'+student_name;
                    document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
                    document.getElementById("songTitle").innerHTML = '<br>'+song_name;
                    document.getElementById("songURL").innerHTML = '<br>'+song_url;
                }
          });

【问题讨论】:

  • 使用index++ 而不是++index

标签: javascript arrays json loops


【解决方案1】:

在您的 for 循环中,您将在每次迭代中重新分配元素的内容。这意味着您在第一次运行 for 时用数组的第一项填充元素,但第二次运行它时,您将元素的内容替换为数组的第二项。所以你只得到最后一项数据。 为了解决这个问题,你应该在每次迭代中“增加”元素的内容,而不是替换它。为了实现这一点,您将 Lines 替换为

document.getElementById("studentName").innerHTML = '<br>'+student_name;

document.getElementById("studentName").innerHTML += '<br>'+student_name;

+= 运算符对字符串进行连接

【讨论】:

    【解决方案2】:

    因为你为元素设置了字符串,所以不要添加字符串。

    替换自:

    document.getElementById("studentName").innerHTML = '<br>'+student_name;
    document.getElementById("studentEmail").innerHTML = '<br>'+student_email;
    document.getElementById("songTitle").innerHTML = '<br>'+song_name;
    document.getElementById("songURL").innerHTML = '<br>'+song_url;
    

    收件人:

    document.getElementById("studentName").innerHTML += '<br>'+student_name;
    document.getElementById("studentEmail").innerHTML += '<br>'+student_email;
    document.getElementById("songTitle").innerHTML += '<br>'+song_name;
    document.getElementById("songURL").innerHTML += '<br>'+song_url;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-09
      • 1970-01-01
      • 1970-01-01
      • 2012-07-20
      • 2011-12-25
      • 2013-08-16
      • 1970-01-01
      相关资源
      最近更新 更多