我有一个来自服务器的 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 View 看起来像:
<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);
}
}
如何在 ListView (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);
});
}
关于javascript - 以列表格式动态显示 JSON 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24055038/