在循环中使用innerHTML不能正确显示json结果集 [英] using innerHTML in a loop is not properly displaying the set of json results

查看:137
本文介绍了在循环中使用innerHTML不能正确显示json结果集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML onclick事件调用一个函数来读取包含JSON语法的Javascript字符串并输出结果,但只显示最后一个结果。

I'm using an HTML onclick event to call a function that will read a Javascript string containing JSON syntax and output the results, but only the last result is being shown.

var resorts = '{ "skiResorts" : [' +
    '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
    '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
    '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';
var obj = JSON.parse(resorts);

function displaySkiResorts() {
    //code
    for (i = 0; i < obj.length; i++) {
        document.getElementById("req8").innerHTML = obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState;
    }
}

为什么这不显示整套滑雪度假村?

Why doesn't this show the entire set of ski resorts?

推荐答案

Nina的回答正确地指出了两个问题(你的循环条件不正确,以及你在每次迭代时覆盖输出元素的 innerHTML )。

Nina's answer correctly points out both issues (that your loop condition is incorrect, and that you are overwriting the innerHTML of the output element on each iteration).

我想指出一个优化。在你的循环体中,在每次迭代中,你

I wanted to point out an optimization. In the body of your loop, on each iteration, you


  1. 按ID查找元素,

  2. 修改其 innerHTML ,这将导致浏览器重新渲染。

  1. lookup an element by ID, and
  2. modify its innerHTML which will cause the browser to re-render.

这两个操作都可以在循环外完成一次。构建您想要插入到输出元素中的HTML,并在一个操作中执行,如此

Both of these operations can be done once, outside the loop. Build-up the HTML you would like to insert into the output element, and do it in one operation, like so

var resorts = '{ "skiResorts" : [' +
    '{ "resortName":"Afton Alps" , "resortState":"Minnesota" },' +
    '{ "resortName":"Alpine Way" , "resortState":"Pennsylvania" },' +
    '{ "resortName":"Alyeska" , "resortState":"Alaska" } ]}';
var obj = JSON.parse(resorts);

function displaySkiResorts() {
    // build array of lines of HTML
    var length = obj.skiResorts.length;
    var html = new Array(length);
    for (var i = 0; i < length; i++) {
        html[i] = obj.skiResorts[i].resortName + " " + obj.skiResorts[i].resortState
    }

    // insert into output, separated by line breaks
    document.getElementById('req8').innerHTML = html.join('<br>');
}
displaySkiResorts();

<div id="req8"></div>

这篇关于在循环中使用innerHTML不能正确显示json结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆