因此,我使用$.getJSON从openweathermap API获取对象。以下是我尝试键入时在控制台中得到的内容:
console.log(data[0])
我想访问"图标"。我试过了:
data[0]["icon"] and data[0].icon
然而,这无济于事。
有人能帮我吗?提前感谢!
$.getJSON
(编辑#1)这是我的代码:
$.getJSON(weatherlink, function(json1) {
$.each(json1, function(key, data) {
// Creating a marker and putting it on the map
var marker = new MarkerWithLabel({
position: points,
labelContent: title,
labelAnchor: new google.maps.Point(22, 20),
labelClass: "label",
// icon: "http://openweathermap.org/img/w/" +data[0]["icon"]+ ".png"
});
markersWeather.push(marker);
marker.setMap(map);
console.log(data[0]);
});
})
weatherlink是一个变量,包含到API的链接。
(编辑#2)
这就是整个数据看起来像的样子
(编辑#3)
当我采取任何一种方式时,它都会给我不明确的定义。
从json1[0]
而不是data
:开始
var icon;
json1 = [{
"icon": "04n"
}];
$.each(json1, function() {
icon = "<img src = http://openweathermap.org/img/w/" + json1[0].icon + ".png>"
});
$('#output').html(icon);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
试试这个(data[key]['icon']):
$.getJSON(weatherlink, function(json1) {
$.each(json1, function(key, data) {
// Creating a marker and putting it on the map
var marker = new MarkerWithLabel({
position: points,
labelContent: title,
labelAnchor: new google.maps.Point(22, 20),
labelClass: "label",
// icon: "http://openweathermap.org/img/w/" +data[0]["icon"]+ ".png"
});
markersWeather.push(marker);
marker.setMap(map);
console.log(data[key]['icon']);
});
})
json1(Object)在循环中,您可以使用以下条件if ( key == 'icon' )
或if ( json1.hasOwnProperty( 'icon' ) ),
如果匹配条件,则使用变量(如数据)或json1[key]
如果要获取循环之外的值,请使用json1['icon'].