I Use .off() Limit One Click . But When Next Page Button Not Work
.off('click') is keypoint,help me limit one chick but have other problem. i hope button recovery click function work.so use .on( ) recovery click but not work . console.log not sh
Solution 1:
See my comments in the code...
$(function() {
// our test object
let testMath = {
1: {
question: "1 + 2 = ?",
options: [3, 6],
answer: 3
},
2: {
question: "2 + 7 = ?",
options: [9, 13],
answer: 9
},
3: {
question: "10 + 4 = ?",
options: [9, 13, 14, 5, 15],
answer: 13
}
};
// constant question page
const questionPage = $('#questionPage');
// render question function
let renderQuestion = function(question) {
// if question id exists in testMath object
if (testMath[question]) {
// render the question
$('.question', questionPage).html(testMath[question].question);
// remove old options
$('.options',questionPage).empty();
// for each question answer options
testMath[question].options.forEach(function(answer) {
// append answer option button to options
$('.options',questionPage).append('<button data-question="' + question + '" data-answer="' + answer + '">' + answer + '</button>');
});
} else {
// empty question page or what ever
$(questionPage).empty();
// test complete alert
alert('Test Complete!');
}
}
// each options button in question page click event
$(questionPage).on('click', '.options BUTTON', function() {
// get this button data values
let question = $(this).data('question');
let answer = $(this).data('answer');
// check answer
checkAnswer(this, question, answer);
});
// check answer function
let checkAnswer = function(elem, question, answer) {
// if answer is correct
if (answer === testMath[question].answer) {
// render this button text correct and switch off event
$(elem).text('correct').off('click');
// 2 sec delay
setTimeout(function() {
// render next question
nextQuestion(question);
}, 2000);
// else answer is wrong
} else {
// render this button text wrong
$(elem).text("wrong");
// 1 sec delay
setTimeout(function() {
// render wrong answer value back this button
$(elem).text(answer);
}, 1000);
}
}
// next question function
let nextQuestion = function(question) {
// render next question
renderQuestion(question + 1);
}
// document on click method to check for all matching targets
$(document).on('click', '#start', function() {
// show the question page
$(questionPage).show();
// render question id 1
renderQuestion(1);
// remove start button
$(this).remove();
});
});
<button id="start">start</button>
<div id="questionPage" style="display: none;">
<h1>Question</h1>
<br>
<p class="question"></p>
<div class="options"></div>
</div>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
Post a Comment for "I Use .off() Limit One Click . But When Next Page Button Not Work"