2016-11-02 74 views
-3

我創建了一個簡單的輸入框,其中用戶將輸入一個簡單的公式(無變量)爲什麼我的jQuery沒有返回我的方程的值?

例如,用戶可以輸入

(5 + 6)* 7 -2

當用戶點擊「Calculate」按鈕時,它會觸發jQuery,它使用.toString()轉換輸入,然後依次解出公式,然後將該值放入元素中。

我比較新,所以我很抱歉,如果我犯了非常嚴重的錯誤。我希望我已經正確地解釋了這一點。

下面是HTML

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="UTF-8"> 
    <title>Interview exercise</title> 
    <script type="text/javascript" src="test.js"></script> 
</head> 
<body> 
    <input name = "equation"/> = <span id="answer"/> 
    <br/> 
    <button>Calculate</button> 
</body> 
</html> 

這裏是JavaScript/jQuery的

$(document).ready(function() { 
    $('button').click(function() { 
     var answer = $("input[name=equation]").toString(); 
     $('#answer') = answer; 
    }); 
}); 
+6

的字符串是不是一個數學操作。你必須解析字符串並基本實現你自己的計算器。 – Derek

+0

嘗試'$(「#answer」).text(eval(answer))' – Isaac

+0

'eval'可以使用,但這不安全。 –

回答

0

我不知道JavaScript的eval()功能。
非常感謝@nnnnnn和@ DanielA.White之間的論證!

關於eval()不安全
這裏是另一個SO answer to explain the risks它,你的情況是不存在的。

因此,這裏是你的HTML計算功能:

$(document).ready(function(){ 
 
    $('button').click(function(){ 
 
     var answer = eval($("input[name='equation']").val()); 
 
     $('#answer').html(answer); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 

 
<input name="equation" value="(5+6) * 7 -2"> = <span id="answer"></span> 
 
<br> 
 
<button>Calculate</button>




編輯
爲了使 .val()功能 安全 ..
但主要是爲了防止不可能的計算,這裏是更新!

這個拉長的腳本從鍵盤過濾「允許的鍵」。

然而,如果一個不可能計算輸入,如4//(68+()
它輸出:«東西是錯在你的公式。»

$(document).ready(function(){ 
 
    var allowedKeys=[48,49,50,51,52,53,54,55,56,57, // 0 to 9 (keyboard) 
 
        96,97,98,99,100,101,102,103,104,105, // 0 to 9 (numpad) 
 
        111,106,109,107,110, // characters/* - + . (numpad) 
 
        189,190,8,32,13 // character - . [backspace] [space] [enter] (keyboard) 
 
        ]; 
 
    var allowedShiftKeys=[51,56,57,48,187,57,48,16]; // characters/* + () [shift] (keyboard + shift) 
 

 
    $("input[name='equation']").on("keydown",function(e){ 
 
     // Clear previous answer 
 
     $('#answer').html(""); 
 

 
     // Check for allowed keydown 
 
     if(($.inArray(e.which,allowedKeys) != -1 && !e.shiftKey) || ($.inArray(e.which,allowedShiftKeys)!=-1 && e.shiftKey)){ 
 
      console.log("Allowed key."); 
 
     }else{ 
 
      // Don't print the key in the input field. 
 
      console.log("Disllowed key."); 
 
      e.preventDefault(); 
 

 
      // Helper to find key number 
 
      console.log(e.which); 
 
     } 
 

 
     // [enter] handler to simulate a button click. 
 
     if(e.which==13){ 
 
      $('button').click(); 
 
     } 
 
    }); 
 

 
    $('button').click(function(){ 
 
     var InputtedValue = $("input[name='equation']").val(); 
 
     
 
     // Remove "//" sequence... Which has the special meaning of a "comment start". 
 
     // Has to be removed before eval() works. 
 
     for(i=0;i<InputtedValue.length;i++){ 
 
      var position = InputtedValue.indexOf("//"); 
 
      if(position!=-1){ 
 
       console.log('Removing "//" occurance.'); 
 
       InputtedValue = InputtedValue.replace("//","/"); 
 
       // Redo the loop from start. 
 
       i=0; 
 
       $("input[name='equation']").val(InputtedValue); 
 
      } 
 
     } 
 

 
     // Try the eval() function... And catch the error if any (Error will come from the inputted formula). 
 
     // Prevents the script from just jamming here. 
 
     try{ 
 
      var answer = eval(InputtedValue); 
 
     } 
 
     catch(error){ 
 
      console.log("ERROR: "+error.message); 
 
     } 
 

 
     // If there is an answer. 
 
     if(typeof(answer)==="number"){ 
 
      $('#answer').html(answer); 
 
     }else{ 
 
      $('#answer').html("Something is wrong in your equation."); 
 
     } 
 
     console.log("Answer: "+answer); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input name="equation" value="(5+6) * 7 -2"> = <span id="answer"></span> 
 
<br> 
 
<button>Calculate</button>

+0

如果用戶不輸入偏見,有沒有什麼辦法可以按照操作順序運行? – flatafor

+0

我現在正在研究一個括號問題......但不是這個。如果缺少括號,則eval失敗並且腳本中止。現在如果沒有任何括號完全是另一場比賽!我沒有注意到'eval()'沒有正確評估它......會檢查我能做什麼,但我會先發布我的實際改進(幾分鐘後)。 –

+0

mmm。從我剛剛做的第一個測試中,當沒有括號時,'eval()** **沒有正確地解釋操作順序。 –

相關問題