[英]Get first object from array using getJSON (JQuery) and 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輸出中的第一個對象放入testfield div,而不是全部。
我嘗試了這個,但是沒有用
$.each(result.weather, function(i,item[0]){
僅供參考:有時,天氣供稿可提供1個以上的天氣。 有時只有一個。
如果要訪問第一個元素,則只需執行此操作即可, 而不是循環:
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
// ^^^
// access the first element in result.weather
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.