使用动态生成的元素创建JavaScript测验

时间:2018-07-18 01:28:12

标签: javascript arrays function button dynamically-generated

**

如何为每个复选框分配答案值?

查看时,此代码会产生(2)个问题,以及每个问题的(4)个可能答案。每个可能的答案旁边都有一个复选框。现在,每个复选框的值都为false,但是我想将每个复选框的值绑定到旁边的可能答案。

有什么想法吗?

**

JavaScript ---------------------------------------------- ---------------------

//JavaScript Quiz
//Questions and answers - multi-dimensional array.
var quizBank = [
["What object runs code continously until an exit condition is met?", "Loop", "Array","Function","Object"],
["Inside which HTML element do we put JavaScript?","javascript",
"js","scripting","script"]
];

//Adds ordered list, list items, and check-boxes. Iterates through array questions and answers.
function printQuiz(quiz) {
var check = "<input type='checkbox' id= 'response' name='response' label='response'>";
    var listHTML = "<ol>"
    for(i = 0; i < quiz.length; i++){
    listHTML += "<li>" + (i + 1) +": " + quiz[i][0] + "</li>" +
  "<li>" + check + quiz[i][1] + "</li>" +
  "<li>" + check + quiz[i][2] + "</li>" +
  "<li>" + check + quiz[i][3] + "</li>" + 
  "<li>" + check + quiz[i][4] + "</li>";
  }
  listHTML += "<ol>";
  return listHTML;
}
//prints printQuiz function to document
document.getElementById("quiz").innerHTML = printQuiz(quizBank);

/* Accessing the values of the checkboxes */
/* First get the ol's li elements under #quiz */
var listItems = document.getElementById("quiz").childNodes[0].childNodes;

/* Iterate through them and look inside for the input */
listItems.forEach(function(element) {

  if (element.childNodes.length > 1) {
   // of the li's who have more than 1 child nodes, the first child node is the checkbox input.
   var checkbox = element.childNodes[0];
   console.log(checkbox.checked);

    });

HTML ---------------------------------------------- -------------------------------

<div>
<h1>
Quiz: Programming Concepts
</h1>
<div id="quiz"></div>
</div>

CSS ---------------------------------------------- --------------------------------

li {
  display: block;
  margin: 1em;

}

1 个答案:

答案 0 :(得分:0)

我想您需要做的就是在输入元素中添加一个“值”属性,其值将是对应于该复选框的响应... (请参见https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox