簡體   English   中英

遍歷 JSON 對象的問題

[英]problem with iterating through the JSON object

在下面的代碼中,我嘗試遍歷 JSON 對象字符串。 但是,我沒有得到所需的輸出。 我在網頁上的輸出看起來像:-

+項目.溫度++項目.溫度++項目.溫度++項目.溫度+

輸出溫度的警報運行良好。 我嘗試通過遍歷 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>

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

應該

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

像您一樣用引號編寫該表達式,只需一遍又一遍地添加一個string Java//Ecmascript 將帶引號的任何內容解釋為字符串文字。

請注意,我還用document.body替換了"body" 這主要是性能 // 訪問原因,所以更好的業力。

您的代碼正在迭代,但是您附加了“+item.temperature+”,難道您不想做類似的事情嗎?

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

或者

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

"+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);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM