[英]dynamically displaying JSON values in list format
我有一個來自服務器的JSON響應,看起來像(注意:數據或多或少,但結構相同)
{
"events": [{
"id": 852157,
"name": "Adelaide v Brisbane",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852157",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}, {
"id": 852217,
"name": "Geelong v Carlton",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852217",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}, {
"id": 852238,
"name": "Carlton v Hawthorn",
"timezone": "Australia/Darwin",
"timezoneOffset": 34200,
"time": 1401987600000,
"timeUtc": "2014-06-05T20:00:00+09:30",
"status": "live",
"wpRef": "852238",
"parentCategoryId": 7,
"parentCategoryName": "Australian Rules",
"categoryId": 9274,
"categoryName": "AFL R26 Matches",
"racingEvent": null,
"raceNumber": null,
"marketCount": 0,
"prefix": null,
"nameSeparator": null,
"markets": [],
"result": null
}]
}
我正在嘗試以列表格式顯示JSON中的“名稱”屬性。 通過onClick方法從服務器檢索數據。 由於返回的JSON數據可能會有所不同(即可能會超過3個事件),因此我希望動態顯示JSON數據。
列表的HTML視圖如下所示:
<div id="someID" class="filtering">
<h2>EVENTS</h2>
<ul>
<li><a href="">Name 1</a>
</li>
<li><a href="">Name 2</a>
</li>
<li><a href="">Name 3</a>
</li>
</ul>
<div class="clear"></div>
</div>
這是我在單擊事件時從服務器獲取JSON時的JS外觀
var navigation = {
sportSubCategoryBindClick: function (id, parentId) {
$("#" + id).live('click', function () {
var thisEl = this,
categoryId = $(this).attr('id');
$.when(ajaxCalls.fetchEventsForCategory(id, parentId, days.fromToday)).done(function (eventsMap) {
// There are no events
if (eventsMap.events.length == 0) {
$('#mainError').show();
$('div.main').hide();
} else {
$('#' + categoryId).addClass('active');
var events = eventsMap.events;
// If there are events
if (events.length > 0) {
navigation.drawAllEvents(events);
}
}
progressIndicator(false);
});
});
},
drawAllEvents: function (events) {
console.log(events);
}
}
我如何在列表視圖(drawAllEvents函數)中從JSON動態填充“名稱”字段,如HTML標記中所述。 可能我需要使用
$.each(result,function(index, value){
// code goes over here
});
但是我不確定如何在我的情況下利用它。
您需要使用從傳遞的events
獲取的數據動態創建新的li
元素,並將其附加到DOM。 像這樣:
drawAllEvents: function (events) {
var $container = $('#someID ul');
$.each(events, function(i, event) {
$('<a />', { text: event.name, href: '#' }).wrap('<li />').parent().appendTo($container);
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.