使用 getJSON (JQuery) 和 for.each 从数组中获取第一个对象
Get first object from array using getJSON (JQuery) and for.each
现在,我列出了多个值,因为我在 for each 循环中附加了对象。
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=51.522035&lon=-0.105732",function(result){
$.each(result.weather, function(i,item){
$('#testfield').append('<p>' + item.main + '</p>');
});
});
});
我只想将 JSON 中的第一个对象输出到测试字段 div,而不是全部。
我试过了,但没用
$.each(result.weather, function(i,item[0]){
仅供参考:有时,天气提要会提供超过 1 个 weather.main。有时,只有一个。
如果您想访问第一个元素,那么只需而不是循环:
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
// ^^^
// access the first element in result.weather
现在,我列出了多个值,因为我在 for each 循环中附加了对象。
$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=51.522035&lon=-0.105732",function(result){
$.each(result.weather, function(i,item){
$('#testfield').append('<p>' + item.main + '</p>');
});
});
});
我只想将 JSON 中的第一个对象输出到测试字段 div,而不是全部。
我试过了,但没用
$.each(result.weather, function(i,item[0]){
仅供参考:有时,天气提要会提供超过 1 个 weather.main。有时,只有一个。
如果您想访问第一个元素,那么只需而不是循环:
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
// ^^^
// access the first element in result.weather