【发布时间】:2018-12-25 19:09:55
【问题描述】:
**
如何为每个复选框分配答案值?
查看时,此代码生成 (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;
}
【问题讨论】:
标签: javascript arrays function button dynamically-generated