Javascript 使用getJSON(JQuery)和for.each从数组中获取第一个对象
现在,我将列出多个值,因为我将从for each循环中附加对象Javascript 使用getJSON(JQuery)和for.each从数组中获取第一个对象,javascript,foreach,getjson,Javascript,Foreach,Getjson,现在,我将列出多个值,因为我将从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>
$(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>');
});
});
});
仅供参考:有时,天气提要提供多个weather.main。有时,只有一个。如果要访问第一个元素,则只需执行该操作,而不是循环:
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
// ^^^
// access the first element in result.weather
$(“#testfield”).append(“”+result.weather[0].main+”');
// ^^^
//访问result.weather中的第一个元素
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
// ^^^
// access the first element in result.weather