1

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 中的定位是如何工作的。

4

2 回答 2

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];
       });
   });
于 2011-12-08T18:36:07.720 回答
0

$.each您可以直接从函数中获取当前值的索引。

$.each(object.storeList.state, function(index, value) {
  var div;
  if(index == 0) {
    div = $('#firstItemDiv');
  } else {
    div = $('#otherItemsDiv');
  }
  div.append(...);
});
于 2011-12-08T18:19:33.523 回答