从对象元素创建单选按钮列表

时间:2013-03-22 18:41:36

标签: javascript

我有一个对象数组,我想获取其中一个对象,并从对象内容中创建一个单选按钮列表。到目前为止,这是我的代码。

var allQuestions = [{question: "This is question number one", choices: ["one", "two", "three", "four"], correctAnswer:"two"},{question: "This is question number two", choices: ["dog", "cat", "bear", "lion"], correctAnswer:"bear"}];

var currentQuestion = allQuestions[1].question;

document.getElementById('question').innerHTML = currentQuestion;

function choiceList() { 

    for (choices in allQuestions[0]) {

    var choiceSelection = document.createElement('input');

    choiceSelection.setAttribute('type', 'radio');
    choiceSelection.setAttribute('name', 'choice');

    document.getElementById('answersBox').innerHTML = choiceSelection;
    }
}

这是我的HTML:

<body>
    <form>
        <label id="question">Question:</label><br />
        <div id="answersBox">
        </div>
        <input type="button" value="save" />
    </form>
  <script src="scripts.js"></script>
</body>

问题是,单选按钮没有显示在answersBox div中。

3 个答案:

答案 0 :(得分:4)

基本上你需要将你创建的每个元素附加到DOM中的正确节点,而不是设置它的HTML值(这不起作用,因为choiceSelection是一个DOM元素而不是表示其HTML代码的字符串)

短暂的改变

document.getElementById('answersBox').innerHTML = choiceSelection;

document.getElementById('answersBox').appendChild(choiceSelection);

我已经实现了在单选按钮旁边添加label HTML元素。

这是一个有效的jsfiddle example

我还想请你注意for (choices in allQuestions[0])在for循环中创建一个名为“choices”的内部变量,它遍历allQuestions [0]的属性,在这种情况下它们是“question”,“选择“和”correctAnswer“。

我认为你打算做的是迭代“选择”数组,这可以这样做: for (choice in question.choices) - 然后在for循环的每一步中,使用数组索引填充选项。

然后,您可以从循环内部访问选择文本,如下所示: question.choices[choice]

答案 1 :(得分:2)

将您的单选按钮添加到for循环中的documentFragment。循环将片段(包含所有选项)附加到document本身。

var frag = document.createDocumentFragment();

for (choices in allQuestions[0]) {

    var choiceSelection = document.createElement('input');
    choiceSelection.setAttribute('type', 'radio');
    choiceSelection.setAttribute('name', 'choice');

    frag.appendChild(choiceSelection);
}

document.getElementById('answersBox').appendChild(frag);

EXAMPLE

修改

Updated with labels

答案 2 :(得分:0)

您需要使用 .appendChild 函数,因为 choiceSelection 是代码中的DOM元素,而不是HTML字符串。

document.getElementById('answersBox').appendChild(choiceSelection);

此外,我没有看到您调用 choiceList()

DEMO