我想要添加到HTML中的JSON数组问题和答案,我可以加载数据,问题是将数据显示到每个相应的部分。只是因为它只显示最后一个问题以及每个部分的数组中的最后一个选项,所以不能完全正确。
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>
答案 0 :(得分: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>');
});
});
});
答案 1 :(得分:0)
$.getJSON('questions.json', function(data)
{
$.each(data, function(index, element)
{
$('h2').text(index.question);
$('.balloons').html(index.option);
});
});