0

データを取得したいjsonファイルがあります。json ファイルが配列に含まれていない場合、すべてが正常に機能します。問題は、.each 関数で正しいデータを選択する方法がわからないことだと思います。json ファイルの例を次に示します。

{
   "chapter1": [
      {
         "title":"This is the title",
         "chapter":"1",
         "verse":"1",
         "text":"text goes here"
      },
      {
         "verse":"4",
         "text":"text goes here"
      },
      {
         "verse":"6",
         "text":"text goes here"
      }
   ],

   "chapter2": [
      {
         "title":"This is the title",
         "chapter":"2",
         "verse":"1",
         "text":"text goes here"
      },
      {
         "verse":"4",
         "text":"text goes here"
      },
      {
         "verse":"6",
         "text":"text goes here"
      }
   ]
}

データを表示するためのループは次のとおりです。

$.getJSON(passages, function(data) {
    $.each(data, function() {
        $('#chapter1 h2').append(this.title);
        $('#chapter1 h3').append(this.chapter);
        $('#verses').append('<li><p>' + this.verse + this.text + '</p></li>');    
    });
});

json ファイルから「chapter2」データを削除すると、すべてが正常に機能します。「chapter1」コンテンツと「chapter2」コンテンツを表示したいと思います。

4

2 に答える 2

1

何らかの理由で、各要素のメンバーの周りに配列を作成しています。titleこれが一貫していると仮定すると、次のchapterようにアクセスできます。

$("#chapter1 h2").append(this[0].title);
$("#chapter1 h3").append(this[0].chapter);

編集: JSON を自分で作成している場合は、おそらくその形式を次のように変更する必要があります。

"chapter": {
   "title": "the title",
   "chapter": "the chapter",
   "verses": [
      {"verse": "1", "text": "text 1"},
      {"verse": "4", "text": "text 2"}
   ]
}

これは$.eachあなたの質問で動作します

于 2012-12-06T17:54:29.660 に答える
0

json の形式が正しくありません。各章の json は次のようになります。

    "chapter1": {
       "title":"this is the title",
       "chapter":"1",
       "verses":[
          {
             "verse":"1",
             "text":"some text"
          },
          {
             "verse":"2",
             "text":"some other text"
          },
      ]
   }

編集: JSON を変更すると、コードは次のようになります。

$.getJSON(passages, function(data) {
    $.each(data, function() {
        $('#chapter1 h2').append(this.title);
        $('#chapter1 h3').append(this.chapter);
        $.each(this.verses,function(){
           $('#verses').append('<li><p>' + this.verse + this.text + '</p></li>');     
        });
    });
});
于 2012-12-06T18:13:30.223 に答える