2016-02-27 34 views
0

我一直在試圖找出如何在隨機數匹配後每次點擊按鈕時執行增量或不匹配。jquery匹配隨機數後增加分數

基本上,如果數字匹配,匹配的計數器會上升。數字不匹配也是一樣。

但目前,櫃檯只會上漲一次。

的jQuery:

$(document).ready(function(){ 
    var a; 
    var b; 
    display(); 
    displayInt(); 

    function displayInt(){ 
     var disInt; 
     disInt = setInterval(display, 2000); 
    }  

    function display() { 

     a = Math.floor((Math.random()*3)+1); 
     $("#number1").html(a); 
     b = Math.floor((Math.random()*3)+1); 
     $("#number2").html(b);  
    } 

    function addScore(){ 
     var correct; 
     var wrong; 
     correct=0; 
     wrong=0; 

     if (a == b){ 
      correct++; 
      $("#correctScore").html(correct); 

     }else{ 

      wrong++; 
      $("#wrongScore").html(wrong);  
     } 
    } 

    $('input[type="button"]').click(function() { 

     a = $("#number2").html(); 
     b = $("#number1").html(); 
     addScore(); 

    });  
}); 

回答

0

correct是在功能addScore地方。每次增加,但每次都設爲0。您需要將correctwrong放在該功能之外。

var correct = 0; 
var wrong = 0; 

function addScore(){ 
    if (a == b){ 
     correct++; 
     $("#correctScore").html(correct); 
    }else{ 
     wrong++; 
     $("#wrongScore").html(wrong);  
    } 
} 
+0

我現在感覺很愚蠢的,太感謝你了! – Yatlax

+0

沒問題!請標記最能回答您問題的答案。 – user707727

0
$(document).ready(function(){ 
    var a; 
    var b; 
    var correct = 0; 
    var wrong = 0; 

    display(); 
    displayInt(); 

    function displayInt() { 
     var disInt; 
     disInt = setInterval(display, 2000); 
    }  

    function display() { 
     a = Math.floor((Math.random()*3)+1); 
     $("#number1").html(a); 
     b = Math.floor((Math.random()*3)+1); 
     $("#number2").html(b);  
    } 

    function addScore() { 

     if (a == b) { 
      correct++; 
      $("#correctScore").html(correct); 

     } else { 
      wrong++; 
      $("#wrongScore").html(wrong);  
     } 
    } 

    $('input[type="button"]').click(function() { 
     a = $("#number2").html(); 
     b = $("#number1").html(); 
     addScore(); 

    });  
});