2017-01-02 49 views
0

我的代碼是這樣的:重置操作

//*Global variables* 
var numStr=""; 
var symbol=""; 
var numero=[]; 
var total=0; 
var totaldisplay=""; 
//... 
//*Event* 
$("button").click(function(){ 
    var key=$(this).html(); 
    // *if statements* 
    if(/\d{1,}|\./.test(key)){ 
      numStr+=key; 
      totalDisplay+=key; 
        } 

    if(/÷|\+|-|×/.test(key)) { 
      symbol=key; 
      numero.push(parseFloat(numStr)); 
      numStr=""; 
      totalDisplay+=key; 

      } 
    if(/=/.test(key)){ 
     numero.push(parseFloat(numStr)); 
     numStr=""; 
     .... 
     total= // *Operations* 

     totalDisplay+="="+total; 


} 

    //.... 
    $("#display2").html(totalDisplay); 

}) 

我覺得我沒字的問題妥善我的第一篇。 它是一個計算器,用戶點擊該按鍵並將其累加在計算器的顯示中。

實施例:

  • 第一次單擊2:numStr="2" and totalDisplay="2"
  • 第二次點擊4:​​。
  • 第三次點擊+:symbol="+"numStr converted into a type number and pushed into the array numero,numStr=""totalDisplay="24+"
  • 第四次點擊9:numStr=9totalDisplay="24+9"
  • 第五點擊=:numStr converted into a type number and push into the array numeronumStr="",它使操作和totalDisplay="24+9=33"

  • (問題)第六點擊7:numStr="97""totalDisplay="24+9=337"。 如何在第一次操作完成後重新開始第二次操作。 因此,在第五次單擊之後,顯示第一個操作,所有變量都設置爲0或空字符串「」;並與第六次點擊 numStr="7"totalDisplay="7"

+0

這是一個無效的JavaScript。 –

+0

您可以點擊'numStr =''來重置它。總數= 0;'在做任何事之前。 – Jai

回答

0

重置點擊處理程序開始處的變量。

$("button").click(function() { 
 
    numStr = ""; 
 
    var key = $(this).html(); 
 
    //if statements * 
 
    if (/\d{1,}|\./.test(key)) { 
 
    numStr += key; 
 
    } 
 
    // .... 
 
})

0

嘗試重置您的單擊事件中的全局變量。

希望這有助於...

0

你應該做這樣的事情 -

var numStr=""; 
var total=0; 

$("button").click(function(){ 
    // Variable should always be defined at top of function definition. 
    var key = $(this).html(); 

    // Early return, it's a good practise 
    if(!(/\d{1,}|\./.test(key))){ 
     return; 
    } 

    numStr = key; 
}) 
0

試試這個

//*Global variables* 
var numStr=""; 
var total=0; 
//... 
//*Event* 
$("button").click(function(){ 
    var numStr = ""; 
    var key=$(this).html(); 
    // *if statements* 
    if(/\d{1,}|\./.test(key)){ 
      numStr+=key;} 
    //.... 
})