基本上,我正在构建一个测验,在测验结束时,当您点击结果时,我会将按钮的类别从nextquestion更改为showResults。然而,问题在于,即使在我更改了类之后,当我单击showResults时,它会进入下一个问题onClick()事件,甚至不会进入showResults。我检查了元素,而按钮的类绝对是showResults,那为什么还会出现呢?
$(".nextquestion").click(function ()
{
if (questionnumberindex < NUM_OF_CHOICES)
{
var newQuestion = '<form>' + '<p> Question' + (questionnumberindex + 1) + ': ' + questionholders[questionnumberindex].question + '</p>';
var bob = questionholders[0].choices[0];
for (var i = 0; i < questionholders[questionnumberindex].choices.length; ++i)
{
newQuestion += '<input type="radio" name="Q' + questionnumberindex + '" value="' + questionholders[questionnumberindex].choices[i] + '">' + questionholders[questionnumberindex].choices[i] + '<br>';
}
newQuestion += "</form>";
questionnumberindex++;
userAnswers.push($('form input[type=radio]:checked').val());
$(".questioncontainer").html(newQuestion);
}
else
{
$(".questioncontainer").text("Quiz Finished!");
$(".nextquestion").text("See your Results!");
$(".nextquestion").addClass("showResults");
$(".nextquestion").removeClass("nextquestion");
}
});
$(".showResults").click(function ()
{
var numCorrect = 0;
//calculate number of answered correctly
var totalQuestions = questionholders.length;
for (var i = 0; i < totalQuestions; i++)
{
if (userAnswers[i] == questionholders[i].correct)
{
numCorrect++;
}
}
var percentageRight = numCorrect / totalQuestions;
//display all the questions
var displayAllQuestions = "You got " + numCorrect + "/" + totalQuestions + "correct!";
for (var i = 0; i < totalQuestions; i++)
{
var currentQuestion = "Question " + i + ": " + questionholders[i].question + "<br>";
for (var j = 0; j < questionholders[i].choices.length; j++)
{
currentQuestion += "<p>" + questionholders[i].choices[j] + "</p>"
}
currentQuestion += "<br>";
displayAllQuestions += currentQuestion;
}
$(".showResults").remove();
$(".questioncontainer").html(displayAllQuestions);
})
});
答案 0 :(得分:2)
当您运行代码以将事件绑定到类showResults
和nextQuestion
时,jQuery会在页面上找到包含这些类的当前项并应用该函数。由于在问题结束之前页面上没有任何内容showResults
,因此showResults
点击功能不会受到任何限制。
一种解决方案是绑定showResults
事件中的nextQuestion
事件:
$(".nextquestion").on("click.NextQuestion", function(){
if(questionnumberindex < NUM_OF_CHOICES) {
//insert Next Question Code Here
}
else {
$(".questioncontainer").text("Quiz Finished!");
$(".nextquestion").text("See your Results!");
$(".nextquestion").addClass("showResults");
$(".nextquestion").removeClass("nextquestion");
//unbind the "Next Question event:
$(this).off("click.NextQuestion");
//bind the Show Results event:
$(this).on("click", function() {
//insert Show Results Code here
});
}
});
此解决方案还使用事件命名空间,以便您可以删除NextQuestion单击事件,而无需删除与该按钮关联的任何其他点击事件。