我正在尝试制作一个测验应用,我想要更新分数。单击下一个问题时未触发单选按钮的更改事件。 https://codepen.io/abhilashn/pen/BRepQz
// JavaScript Document
var quiz = { "JS" : [
{
"id" : 1,
"question" : "Inside which HTML element do we put the JavaScript?",
"options" : [
{"a": "<script>",
"b":"<javascript>",
"c":"<scripting>",
"d":"<js>"}
],
"answer":"<script>",
},
{
"id" : 2,
"question" : "What is the correct JavaScript syntax to change the content of the HTML element below.",
"options" : [
{"a": " document.getElementById('demo').innerHTML = 'Hello World!';",
"b":" document.getElementByName('p').innerHTML = 'Hello World!';",
"c":" document.getElement('p').innerHTML = 'Hello World!';",
"d":" #demo.innerHTML = 'Hello World!';"}
],
"answer":" document.getElementById('demo').innerHTML = 'Hello World!';",
}
]
}
var quizApp = function(){
this.score = 0;
this.qno = 1;
this.currentque = 0;
var totalque = quiz.JS.length;
this.displayQuiz = function(cque) {
this.currentque = cque;
if(this.currentque < totalque) {
$("#qid").html(this.qno++);
$("#question").html(quiz.JS[this.currentque].question);
$("#question-options").html("");
for (var key in quiz.JS[this.currentque].options[0]) {
if (quiz.JS[this.currentque].options[0].hasOwnProperty(key)) {
//console.log(key + " -> " + quiz.JS[this.currentque].options[0][key]);
$("#question-options").append(
"<div class='form-check option-block'>" +
"<label class='form-check-label'>" +
"<input type='radio' class='form-check-input' name='option' id='q"+key+"' value='" + quiz.JS[this.currentque].options[0][key] + "'>" +
quiz.JS[this.currentque].options[0][key] +
"</label>"
);
}
}
} else {
return alert("Your score: " + this.score) ;
}
}
this.checkAnswer = function(option) {
var answer = quiz.JS[this.currentque].answer;
option = option.replace(/\</g,"<") //for <
option = option.replace(/\>/g,">") //for >
console.log(answer);
console.log(option);
if(option == quiz.JS[this.currentque].answer) {
this.score = this.score + 1;
console.log(this.score);
}
}
this.changeQuestion = function(cque) {
this.currentque = this.currentque + cque;
this.displayQuiz(this.currentque);
}
}
var jsq = new quizApp();
$(document).ready(function() {
jsq.displayQuiz(0);
$('input[type=radio][name=option]').change(function(e) {
e.preventDefault();
if (this.checked) {
jsq.checkAnswer(this.value);
}
});
});
$('#next').click(function(e) {
e.preventDefault();
jsq.changeQuestion(1);
});
答案 0 :(得分:2)
您只对已存在的元素应用事件处理程序,而不是稍后将创建的元素。
事件处理程序应该位于所有未来元素的父元素上。
像这样:
$('#question-options').on('change', 'input[type=radio][name=option]', function(e) {
// code
});
来自on
上的jQuery文档:
事件处理程序仅绑定到当前选定的元素;它们必须在您的代码调用.on()时存在。为了确保元素存在且可以选择,[...]使用委托事件来附加事件处理程序。
委托事件的优势在于它们可以处理来自稍后添加到文档的后代元素的事件。通过选择附加委托事件处理程序时保证存在的元素,您可以使用委派事件来避免频繁附加和删除事件处理程序。