【问题标题】:problem with iterating through the JSON object遍历 JSON 对象的问题
【发布时间】:2010-07-12 17:08:58
【问题描述】:

在下面的代码中,我尝试遍历 JSON 对象字符串。但是,我没有得到想要的输出。我在网页上的输出类似于:-

+item.temperature++item.temperature++item.temperature++item.temperature+

输出温度的警报运行良好。我尝试通过遍历 JSON 对象字符串来访问值的部分似乎不起作用。有人可以帮我解决这个问题吗?

代码

<body>
    <script>
    $.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',
      function(data) {
        $.each(data.weatherObservations, function(i, item) {
          $("body").append("+item.temperature+");
          if (-i == 3-) return false;
        });
        alert(data.weatherObservations[0].temperature);
      });
    </script>
</body>

【问题讨论】:

    标签: javascript jquery json iterator


    【解决方案1】:

    不要在$("body").append("+item.temperature+");.append() 部分中使用引号。

    应该是

    $(document.body).append(item.temperature);
    

    像您一样用引号编写该表达式,只需一遍又一遍地添加string。 Java//Ecmascript 将任何带引号的内容解释为字符串文字。

    请注意,我还将"body" 替换为document.body。这主要是性能//访问原因,所以更好的业力。

    【讨论】:

      【解决方案2】:

      您的代码正在迭代,但您附加了“+item.temperature+”,您不想做类似的事情

      $("body").append("Temp is " + item.temperature);
      

      $("body").append(item.temperature);
      

      【讨论】:

        【解决方案3】:

        "+item.temperature+" 表示 "+item.temperature+" 的字符串

        "pre" + item.temperature + "post" 会将变量连接到字符串。

        $.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2', 
          function (data) {
            $.each(data.weatherObservations, function (i, item) {
                $("body").append(item.temperature + ",");
                if (i == 3) return false;
            });
            alert(data.weatherObservations[0].temperature);
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-01-11
          相关资源
          最近更新 更多