[英]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.