gpt4 book ai didi

javascript - 用对象动态填充 div

转载 作者:行者123 更新时间:2023-11-28 17:52:23 25 4
gpt4 key购买 nike

我想用问题 id 填充一个 div,其中包含 4 个琐事问题和一个 for 循环的答案。不幸的是,正如我现在所拥有的,我的代码只提出了问题 4 及其对 div 的答案,任何关于我做错了什么的想法将不胜感激。

$(function() {
var trivia = [{
question: "01. What is CSS?",
answers: ["Casscading Style Sheets", "Carrot steamed soup", "Corruoted style sheets", "Casscading stairs sheets"],
correctAnswer: 0
},{
question: "02. Q2?",
answers: ["1", "2", "3", "4"],
correctAnswer: 1
},{
question: "03. Q3?",
answers: ["1", "2", "3", "4"],
correctAnswer: 3
},{
question: "04. Q4?",
answers: ["1", "2", "3", "4"],
correctAnswer: 3
}];

$("#startButton").on('click', function populate() {
var testDiv = document.createElement("div");
for (var i = 0; i < trivia.length; i++) {
testDiv.innerHTML = '<h3>' + trivia[i].question + '</h3>' + '<div><form><p><input type="radio" name="answer" value="right">' +
trivia[i].answers[0] + '</p>' +
'<p><input type="radio" name ="answer" value="2">' + trivia[i].answers[1] + '</p>' +
'<p><input type="radio" name ="answer" value="3">' + trivia[i].answers[2] + '</p>' +
'<p><input type="radio" name ="answer" value="4">' + trivia[i].answers[3] + '</p>' +
'<p></form> </div>';
}
var questionsDiv = document.getElementById('questions');
questionsDiv.appendChild(testDiv);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="questions"></div>

<button id="startButton" type="button">Start</button>

最佳答案

您在每个循环中都覆盖了您的innerHtml。

$(function() {
var trivia = [{
question: "01. What is CSS?",
answers: ["Casscading Style Sheets", "Carrot steamed soup", "Corruoted style sheets", "Casscading stairs sheets"],
correctAnswer: 0
},{
question: "02. Q2?",
answers: ["1", "2", "3", "4"],
correctAnswer: 1
},{
question: "03. Q3?",
answers: ["1", "2", "3", "4"],
correctAnswer: 3
},{
question: "04. Q4?",
answers: ["1", "2", "3", "4"],
correctAnswer: 3
}];

$("#startButton").on('click', function populate() {
var testDiv = document.createElement("div");
for (var i = 0; i < trivia.length; i++) {
testDiv.innerHTML += '<h3>' + trivia[i].question + '</h3>' + '<div><form><p><input type="radio" name="answer" value="right">' +
trivia[i].answers[0] + '</p>' +
'<p><input type="radio" name ="answer" value="2">' + trivia[i].answers[1] + '</p>' +
'<p><input type="radio" name ="answer" value="3">' + trivia[i].answers[2] + '</p>' +
'<p><input type="radio" name ="answer" value="4">' + trivia[i].answers[3] + '</p>' +
'<p></form> </div>';
}
var questionsDiv = document.getElementById('questions');
questionsDiv.appendChild(testDiv);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="questions"></div>

<button id="startButton" type="button">Start</button>

关于javascript - 用对象动态填充 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45207138/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com