2014-04-17 102 views
1

我想打電話給一個局部變量,totalYes,jQuery的。點擊功能之外。要做到這一點,我應該把它變成一個全局變量,對吧?原來,代碼看起來像:在jquery.click函數外部使用變量?

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12]; 

var answers2 = [answers2array12items]; 

$("#submmit").click(function() { 
    var totalYes=0; 
    function checkAnswers() { 
     for(var i=0; i<answers.length; i++) { 
      var userAnswer = document.getElementById("b"+i).value.toLowerCase(); 
      if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) { 
       totalYes++; 
       $("#correcto").show(); 
      } else { 
       $("#incorrecto").show(); 
      } 
     } 
    } 
    checkAnswers(); 
    alert(totalYes); 
}); 

,它工作正常,但是,我想用它在:

$("total").click(function(){ 
    alert(totalYes); 
}); 

所以我把totalYes,並使其「全局」,在函數外。新版本:

var answers = [thing1, thing2, thing3, thing4, thing5, thing6, thing7, thing8, thing9, thing10, thing11, thing12]; 

var answers2 = [answers2array12items]; 

var totalYes = 0; 

$("#submmit").click(function() { 
    function checkAnswers() { 
     for(var i=0; i<answers.length; i++) { 
      var userAnswer = document.getElementById("b"+i).value.toLowerCase(); 
      if (answers.indexOf(userAnswer.toLowerCase()) !== -1 || answers2.indexOf(userAnswer.toLowerCase()) !== -1) { 
       totalYes++; 
       $("#correcto").show(); 
      } else { 
       $("#incorrecto").show(); 
      } 
     } 
    } 
    checkAnswers(); 
    alert(totalYes); 
}); 

但在新的代碼,而不是增加1至totalYes每一個正確的答案,並增加這樣totalYes:「1,2,3,4,5,6,7, 8,9,10,11,12「,它增加爲:」1,3,6,10,15,21,27,33,39,46,54「。我試着改變checkAnswers()裏面的totalYes修飾符,從totalYes ++;總計是+ = 1,但問題仍然存在。

另外,我想知道,爲什麼提示框顯示了每一次的兩倍,而不是僅僅一次?

編輯:這裏的HTML和CSS#合計和#submmit:

<div class="nextsa1" id="total"><strong>TOTAL</strong></div> 

<input type="button" id="submmit" value="GO"> 
+1

小提琴證明問題將是更好的調試 –

+2

我懷疑你實際上有兩個事件處理程序都在運行。 – Barmar

+0

@ andryuu87如果可能,可以發佈'html'?例如'',爲'$(「submmit」)','$(「total」)''''''''''由於 – guest271314

回答

1

你的代碼出現搜索的完整的答案列表中的每個時間,它是在進入一個新的答案,用戶調用。因此,在每次調用時,Test Inside your Click處理程序對當前和以前的所有答案都成功,這解釋了totalYes變量的Delta模式。

解決方法:初始化totalYes以0作爲Click處理程序中的第一個指令。