【发布时间】:2017-05-28 11:33:34
【问题描述】:
我正在尝试制作一个测验应用程序,我希望更新分数。单击下一个问题时未触发单选按钮的更改事件。 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);
});
【问题讨论】:
标签: javascript jquery