2016-05-22 17 views
0

HTMLに追加する質問と回答のJSON配列を取得しました。データをうまく読み込めません。問題はそれぞれのセクションにデータを表示しています。各セクションの配列の最後の質問と最後のオプションしか表示されていないので、それを正しく取得できません。JSONデータをhtml forループにロード

JSONデータは次のとおりです。

[ 
    { 
     "question": "What kind of event are you looking for", 
     "option": [ 
      "Incentive Trip", 
      "Birthday Party", 
      "Insipiring Holiday", 
      "Memorable Experience", 
      "Wedding", 
      "Conference", 
      "Exciting Concert", 
      "Crazy Festival", 
      "Product Launch", 
      "Stag Do", 
      "Hen Do", 
      "Surprise for loved ones" 
     ] 
    }, 
    { 
     "question": "What are you looking to achieve?", 
     "option": [ 
      "Bond up with your Clients", 
      "Reward the best performers", 
      "Say thank you to your team" 
     ] 
    }, 
] 

jQueryのコードは次のとおりです。

$.getJSON('questions.json', function(data) { 
    $.each(data, function(index, element) { 

     // Add the question 
     $.each($('section'), function() { 
      $('h2').text(element.question); 
     }); 

     $.each($('section .balloons'), function() { 
      for(var i = 0; i < $(element.option).length; i++) { 
       $('.balloons').html('<p>'+ element.option[i] +'</p>'); 
       console.log(element.option[i]); 
      }; 

     }); 


    }); 
}); 

HTMLは次のとおりです。

<section class="play" id="eventType"> 
     <h2></h2> 
     <div class="balloons"></div> 
    </section> 
    <!-- Achieve --> 
    <section class="achieve" id="achieve"> 
     <h2></h2> 
     <div class="balloons"> 
      <div class="balloon"></div> 
     </div> 
    </section> 

答えて

2

あなたはこの

を試すことができますそれでも唯一の配列から最後の質問と最後のオプションで引っ張っ
$.getJSON('questions.json', function(data) 
{ 
    $.each($("section"), function (index){ 
     var result = data[index]; 
     var $ballons = $(this).find(".balloons"); 
     $(this).find("h2").html(result.question); 

     $.each(result.option, function(idx) { 
      $ballons.append('<p>'+ result.option[idx] +'</p>'); 
     });   
    }); 
}); 

FIDDLE DEMO HERE

+0

私は次のエラーを取得:キャッチされない例外TypeErrorを:プロパティを読み取ることができません未定義 –

+0

の「質問」は、両方のデータをCONSOLE.LOGにしてください&結果彼らはあなたに未定義を示しましたか? –

+0

私はデータを取得しますが、私はまた未定義を取得します。私は、HTMLで定義されたセクションが他にもたくさんあります。 –

1
$.getJSON('questions.json', function(data) 
{ 
    $.each(data, function(index, element) 
    { 
     $('h2').text(index.question); 
     $('.balloons').html(index.option); 

    }); 

}); 
+0

:( –

関連する問題