javascript - Recursive function causes other calls to fire multiple times -


i'm working on quiz game, wherein user presented quote , has guess author:

  function startgame(quotes) {     askquestion(quotes[0], 0, 0);      function askquestion(quote, question, score) {       var q = "<span class='quo'>&ldquo;</span><em>" + quote.quote + "</em><span class='quo'>&rdquo;</span>";       $('.choice').css('visibility', 'visible');       $('#questions').html(q);       $('.choice').click(function(e){         $('.choice').css('visibility', 'hidden');         e.preventdefault();         var nextq = (question + 1);         var btntxt = (nextq < number_of_questions ? 'next...' : 'final results');         if ($(this).attr('data-author') === quote.author) {           score++;           $('#questions').html('<h1>correct.</h1><a class="btn next">' + btntxt + '</a>');           document.getelementbyid('win').play();         } else {           $('#questions').html('<h1>wrong.</h1><a class="btn next">' + btntxt + '</a>');           document.getelementbyid('lose').play();         }         $('#questions').append('<h4>score: ' + score + '/' + nextq + '</h4>');         $('.next').on("click", function(){           question += 1;           if (question < number_of_questions) {             askquestion(quotes[question], question, score);           } else {             tallyscore(score);           }         });       });     }   } 

when question asked, askquestion() function called again if fewer 6 questions have been asked.

everything works great, i'm having issues sound effects. if user gets answer right , answer wrong, both "win" , "lose" sound effects played simultaneously.

my guess has recursively calling askquestion() -- seems entire "history" of function looped through. having similar problem earlier — on correct answers, score global variable incremented number of correct answers (instead of one).

any idea how can fix that? thanks!

edit: requested, here's jsfiddle.

easy fix actually. re-attaching click listener on , over, remove each time gets set.

change

  $('.choice').click(function (e) { 

to

  $('.choice').off().click(function (e) { 

http://jsfiddle.net/nadym/


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -