我正在进行测验,并希望在用户点击“下一步”按钮时添加带有答案选项的复选框。这是代码:
<!DOCTYPE html>
<html>
<head>
<title>quiz</title>
<link href="main.css" rel="stylesheet" type="text/css">
</head>
<body>
<p id="qstn">1. Which of these cities are located in South America?</p>
<form id="first_form">
</form>
<form>
<input id="nextqstn" type="button" name="nextbutton" value="Next" onclick="changeQuestion()">
</form>
<script src="script.js"></script>
</body>
</html>
script.js文件:
var allQuestions = [{question: "1. Which of these cities are located in South America?", answers:
["Montevideo", "Kyoto", "Quito", "Mexico City", "Toulouse"], correctAnswer: ["Montevideo", "Quito"]}, {question:
"2. Which of moons of Saturn is the biggest?", answers: ["Titan", "Rhea", "Iapetus"], correctAnswer: "Titan"},
{question: "3. Which of these composers was considered as impressionist?", answers: ["Robert Schumann",
"Frederic Chopin", "Maurice Ravel"], correctAnswer: "Maurice Ravel"}];
function changeQuestion(){
var qstn = document.getElementById("qstn").innerHTML.charAt(0) - 1;
qstn++;
document.getElementById("qstn").innerHTML = allQuestions[qstn].question;
addAnswers();
function addAnswers(){
var numberOfAnswers = allQuestions[qstn].answers.length;
var container = document.getElementById("first_form");
while (container.hasChildNodes()){
container.removeChild(container.firstChild);
}
for (i = 0; i < allQuestions[qstn].answers.length; i++){
var input = document.createElement("input");
input.appendChild(document.createTextNode(allQuestions[qstn].answers[i]));
input.type = "checkbox";
input.name = "answer"
container.appendChild(input);
container.appendChild(document.createElement("br"));
}
}
}
问题是,由于“输入”元素按原样添加(复选框以及var allQuestions的答案(例如,可以在歌剧蜻蜓中看到)),浏览器仅显示复选框。谁能解释为什么会这样?感谢
答案 0 :(得分:0)
我认为这是因为您在输入中添加了文本节点:
input.appendChild(document.createTextNode(allQuestions[qstn].answers[i]));
虽然您应该在输入后添加它们:
var textNode = document.createTextNode(allQuestions[qstn].answers[i]);
container.appendChild(input);
container.appendChild(textNode);
答案 1 :(得分:0)
有些观点
<script></script>
块中。<script src="script.js"></script>
放在</body>
标记之后。试试这个
var textNode = document.createTextNode(allQuestions[qstn].answers[i]);
container.appendChild(input);
container.appendChild(textNode);