JSON:
{
"storeList":{
"state":[
{
"stateName":"Maine",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 2",
"storeID":"store2",
"storeURL":"http:\/\/www.sitename.com"
},
{
"storeName":"Store 3",
"storeID":"store3",
"storeURL":"http:\/\/www.sitename.com"
}
]
},
{
"stateName":"Connecticut",
"store":[
{
"storeName":"Store 1",
"storeID":"store1",
"storeURL":"http:\/\/www.sitename.com"
}
]
}
]
}
}
和我在页面上渲染的功能:
$(document).ready(function() {
var object;
$.getJSON('xml/storeList.json', function(json) {
object = json;
$('#storeList').append('<ul/>')
$.each(object.storeList.state, function() {
var list = $('#storeList ul'),
listItem = $('<li/>'),
html = listItem.append($('<h3/>').text(this.stateName));
$.each(this.store, function() {
listItem.append($('<a />').attr('href', this.storeURL).text(this.storeName));
});
list.append(html)
});
});
});
我想获取第一个“状态”对象并将其附加到与其他对象不同的div。 谢谢!我意识到json是一个数组,但我不确定json中的定位是如何工作的。
答案 0 :(得分:1)
您的问题标题表示您要分离第一个元素。为此你可以使用拼接:
$.getJSON('xml/storeList.json', function(json) {
object = json;
var firstState = object.storeList.state.splice(0, 1)[0];
//first state has been removed from the array and can be added anywhere
$.each(object.storeList.state, function() {
//each will now iterate over the remaining elements
});
});
或者,如果您不想删除它,您可以使用它,然后使用旧式的非jQuery for循环循环其余项:
$.getJSON('xml/storeList.json', function(json) {
object = json;
var currentState;
var firstState = object.storeList.state[0];
for(var i = 1; i < object.storeList.state.length; i++) {
currentState = object.storeList.state[i];
});
});
答案 1 :(得分:0)
您可以直接从$.each
函数获取当前值的索引。
$.each(object.storeList.state, function(index, value) {
var div;
if(index == 0) {
div = $('#firstItemDiv');
} else {
div = $('#otherItemsDiv');
}
div.append(...);
});