简体   繁体   中英

jQuery onclick call function

I've found a script that converts json file into quiz using jquery.

I am playing with it's code for almost a day now and I can't come with what I wanted to have.

Functions quiz().init(); and quiz().bindSubmit(); are called when page loaded.

What I want is the START button must be clicked first to load the Quiz.

$("#start").click(function(){
    currentQuestion = 0;
    questionCount = 0;
    answerArray = [];
    infoMode = false;
    gotData = false;
    inMemoryData = [];
    quiz().init();
    quiz().bindSubmit();
});

HTML:

<button type="button" id="start">Start</button>
<div id="quiz-content"></div>

It works at first click of START button also in the next clicks, it successfully reset the quiz and goes back to #1.

But the problem is after the first click of Start Button , the quiz won't work normally when submitting the quiz. The quiz began to stucked in #1.

For better understanding, JSfiddle here .

Edited: Basically when the user click start button more than once,the quiz gets started from the beginning ,but didn't get to the next question(Gets stuck on the 1st question itself)

When you call bindSubmit function, inside it you are attaching to the submit event of the #quizForm . So when you press Start button twice, there two event handlers attached to the same event and that is because it is not behaving as it should be. So inside the bindSubmit function you need always disconnect all submit handlers ( $(document).off('submit'); ), like this:

var bindSubmit = function () {
  $(document).off('submit');
  $(document).on('submit', '#quizForm', function (event) {
    event.preventDefault();
    next(this);
    quiz().init();
  });
};

Here is your original fiddle with mentioned update https://jsfiddle.net/t4p8x02b/35/

There are couple of things i observed in your code, which needs to be rectified for better management of code:

  • There is no need to expose init() outside your quiz library, for first time initialization, you can call init() before your return from the library(end of quiz() module code).
  • Also exposing init() makes your quiz() module vulnerable since it can be modified by any external program which could spoil your entire quiz() logic.
  • Inside bindSubmit() , you dont need to re-initialize your quiz instance to call init() , rather just call init() (refer below code snippet), your event handler will call it without any error [This is the magic of Closure] .

bindSubmit():

    $(document).on('submit', '#quizForm', function (event) {
         event.preventDefault();
         next(this);
         init();
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM