2016-05-22 34 views
0

得到了一個JSON陣列的問題和答案,我想要添加到HTML中,我可以在數據加載罰款,問題顯示數據到每個部分。只是不能完全正確,因爲它只顯示數組中每個部分的最後一個問題和最後一個選項。將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

我收到以下錯誤最後選項:遺漏的類型錯誤:無法讀取未定義 –

+0

嘗試CONSOLE.LOG兩個數據的特性「問題」 &結果。他們是否顯示你未定義? –

+0

我得到的數據,但我也得到一個未定義的。我在HTML中定義了更多的部分,JS可以用來填充這些部分嗎? –

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

    }); 

}); 
+0

仍然只拉在最後一題,從陣列:( –

相關問題