在DOM中创建的文本节点在浏览器中不可见

时间:2013-11-28 06:55:43

标签: javascript html dom

我正在进行测验,并希望在用户点击“下一步”按钮时添加带有答案选项的复选框。这是代码:

<!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的答案(例如,可以在歌剧蜻蜓中看到)),浏览器仅显示复选框。谁能解释为什么会这样?感谢

2 个答案:

答案 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)

有些观点

  1. 首先,您需要知道任何javascript代码都应该包含在<script></script>块中。
  2. 在您的代码中,您需要将<script src="script.js"></script>放在</body>标记之后。
  3. 创建textnode时出错了,即你将它附加在错误的输入元素中。
  4. 试试这个

    var textNode = document.createTextNode(allQuestions[qstn].answers[i]);
    container.appendChild(input);
    container.appendChild(textNode);