【发布时间】:2020-07-08 22:03:55
【问题描述】:
我想为每个无线电输入点击附加一个事件侦听器,以便我可以检索该无线电输入的值并将其分配为 allQuestions 数组中当前问题对象中的一个新属性的值。
我不知道为什么我很难让choice.addEventListener 工作。
我的 HTML:
<div id="quiz"></div>
<button id="button">Next</button>
我的 JavaScript:
var allQuestions = [{question: "What is the capital of the Czech Republic?",
choices: ["Skopje", "Budapest", "Prague", "Bucharest"],
correctAnswer: 2},
{question: "When was the Declaration of Independence signed?",
choices: ["1492", "1776", "1812", "1791"],
correctAnswer: 1}];
var quiz = document.getElementById("quiz");
var index = -1;
var next = function() {
index += 1;
quiz.innerHTML = "";
for (var i = 0; i < allQuestions[index]['choices'].length; i++) {
var choice = document.createElement('input');
choice.type = 'radio';
choice.name = 'choices';
choice.value = i;
choice.addEventListener('click', function() {
alert('hi');
});
quiz.appendChild(choice);
quiz.innerHTML += allQuestions[index]['choices'][i] + '<br>';
}
};
var button = document.getElementById('button');
button.addEventListener('click', next);
【问题讨论】:
-
您是否尝试在添加之前将事件处理程序添加到选项中?
-
@rmjoia,是的,但是如果我将
choice.addEventListener放在quiz.appendChild(choice);之后,它仍然不起作用
标签: javascript radio-button addeventlistener dynamically-generated