2014-02-19 24 views
0

我一直在開發一個jQuery測驗,我已經能夠將每個答案的值加在一起,我想添加一個函數來測驗,將允許特定值添加到一組每個問題之後的變量已被回答。增量分數,jQuery測驗

我已經包含了一個jsFiddle,在任何值被註冊之前,您可以看到每個問題何時單擊其第三個問題,並且如果添加了第四個問題,則增加的值會被添加三次。

的jsfiddle:http://jsfiddle.net/jamcrowe/ta7LZ/1/

  // Answers to each question add these values to finalResult 
    var value = { 
    'question0' : { one: 1, two: 2, three: 3, four: 4 }, 
    'question1' : { one: 1, two: 2, three: 3, four: 4 }, 
    'question2' : { one: 1, two: 2, three: 3, four: 4 } 
    }; 

      // The next question to present after each response 
    var END = null; 
    var nextQuestion = { 
     'question0' : { one: 'question1', two: 'question1', three: 'question1', four: 'question1', }, 
     'question1' : { one: 'question2', two: 'question2', three: 'question2', four: 'question2', }, 
     'question2' : { one: END, two: END, three: END, four: END, }, 
    }; 

    // Show just the first question 
    $('.ques').hide(); 
    $('#question0').fadeIn(); 

    var outcome = 0; 

    $('.option').click(function(){ 

     increment(); 

     var answer = $(this).attr('value'); 
     var question = $(this).attr('name'); 

     outcome += value[question][answer]; 

     $('#' + question).delay(500).fadeOut(function(){ 
     var questionNext = nextQuestion[question][answer]; 
     if (questionNext == END){ 
      var finalResult = 'result ' + outcome; 
      alert("Values added together : " + finalResult); 
     } 
     else { 
      $('#' + questionNext).delay(2000).fadeIn(1000); 
     } 
    }); 

    }); 

    var online = 0; 
    var creative = 0; 
    var technical = 0; 
    var analyst = 0; 
    var managerial = 0; 

    function increment() { 
    $('#q1a').click(function(){ 
     creative +=5; 
     online ++; 
     managerial ++; 

    }); 
    $('#q2a').click(function(){ 
     creative +=5; 
     online ++; 
     managerial ++; 

    }); 
    $('#q3a').click(function(){ 
     creative +=5; 
     online ++; 
     managerial ++; 

    }); 
    $('#q4a').click(function(){ 
     creative +=5; 
     online ++; 
     managerial ++; 

    }); 
    alert(creative); 
    } 
+0

http://jsfiddle.net/jamcrowe/ta7LZ/1/ –

回答

1

有兩部分的答案,你看到的:

首先,每次運行increment功能的時候,你綁定一個新的單擊事件的div s與idq1a,q2aq3aq4a。這意味着如果您將多個click事件綁定到一個div,則一次點擊就會多次運行該事件。

接下來,在q1a,q2a等這些點擊事件之後,運行$('.option')點擊事件。因此,當您在0點看到第二個警報時,變量creative被添加到此警報觸發後。

$('#q2a').click(function(){ 
    creative +=5; 
    online ++; 
    managerial ++; 
    console.log("q2a",creative); 
}); 

總體而言,您應該設置您的increment函數內的點擊事件在腳本的開頭或識別其格是:你可以通過添加一個console.log()聲明您q2a click事件裏面這樣看這個點擊並根據此添加值 - 不要添加這麼多點擊事件。

希望這會有所幫助 - 如果您有任何問題,我可以回答更多問題!