[英]Get data from nested array
如何在仍然引用item.id
從此JavaScript對象中的每個markers
獲取routes
數組中的每個id
:
{
"markers": [
{
"id": "77475",
"smsCode": "77475",
"name": "Abbey Sports Centre",
"stopIndicator": "Y",
"towards": "Goodmayes or Upney",
"direction": "sw",
"lat": 51.53472971807365,
"lng": 0.07973349341716908,
"routes": [
{
"id": "62",
"name": "62"
},
{
"id": "287",
"name": "287"
},
{
"id": "368",
"name": "368"
},
{
"id": "387",
"name": "387"
},
{
"id": "687",
"name": "687"
}
]
}
]
}
實際結果中有更多標記,為節省空間將其縮短。 這是我的jQuery。
$.each(data.markers, function(i,item){
$.each(item.routes, function(i,routes){
$('<span>').html(routes.id + " ").appendTo("#p_" + item.id);
//alert("#p_" + item.id + " " +routes.id);
});
$('<li>').html(
"<a href=#_" + item.id +" onclick=getBusListingForStop(" + item.id + ");><h2>" + item.name + " (Stop " + item.stopIndicator + ") to " + item.towards + "</h2><p id='p_" + item.id + "'>Buses: " + item.lat + " " + item.lng + "</p></a>"
).appendTo('#stopListing');
});
示例: http : //jsbin.com/uniyar/2/edit
愚蠢的我,代碼順序是錯誤的,在創建實際元素之前,我正在運行第二個循環。 重新訂購,可以正常工作。
$.each(data.markers, function(i,item){
$('<li>').html(
"<a href=#_" + item.id +" onclick=getBusListingForStop(" + item.id + ");><h2>" + item.name + " (Stop " + item.stopIndicator + ") to " + item.towards + "</h2><p id='p_" + item.id + "'>Buses:</p></a>"
).appendTo('#stopListing');
$.each(item.routes, function(i,routes){
$('<span>').html(routes.id + " ").appendTo("#p_" + item.id);
//alert("#p_" + item.id + " " +routes.id);
});
});
愚蠢的我,代碼順序是錯誤的,在創建實際元素之前,我正在運行第二個循環。 重新訂購,可以正常工作。
$.each(data.markers, function(i,item){
$('<li>').html(
"<a href=#_" + item.id +" onclick=getBusListingForStop(" + item.id + ");><h2>" + item.name + " (Stop " + item.stopIndicator + ") to " + item.towards + "</h2><p id='p_" + item.id + "'>Buses:</p></a>"
).appendTo('#stopListing');
$.each(item.routes, function(i,routes){
$('<span>').html(routes.id + " ").appendTo("#p_" + item.id);
//alert("#p_" + item.id + " " +routes.id);
});
});
這是一個小范圍問題,您可以輕松解決...
$.each(data.markers, function(i,item){
$('<li>').html(
"<a href=#_" + item.id +" onclick=getBusListingForStop(" + item.id + ");><h2>" + item.name + " (Stop " + item.stopIndicator + ") to " + item.towards + "</h2><p id='p_" + item.id + "'>Buses:</p></a>"
).appendTo('#stopListing');
createEachFunction = function(item){return function(i,routes){
$('<span>').html(routes.id + " ").appendTo("#p_" + item.id);
//alert("#p_" + item.id + " " +routes.id);
}
}
myEachFunction = createEachFunction(item);
$.each(item.routes, myEachFunction);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.