获取一个输入字段以获取两个输入的值并执行Math.pow()

时间:2016-01-16 21:20:50

标签: javascript jquery

我有一个带有按钮的JavaScript / jQuery计算器,它通过函数执行将第一个输入的整数提升到第二个输入整数的数学运算:

$('#button-power').click(function(form){
var base = this.form.display.value; // the 1st value entered by user

setTimeout (function(){
      $("#disp").val('0'); // resets the calc display to 0 to accept second argument
    },0.5);

$("#button-enter").click(function(form){ // the 'equals' button
    var exponent = this.form.display.value; // the 2nd value entered by user
    var result = Math.pow(base,exponent);

setTimeout (function (form){
      $('#disp').val(result);
    },1);
    });

});

其中#disp是计算器显示。该功能正常工作并产生正确的答案,但在使用电源按钮执行计算后,它会导致计算器上的其他按钮表现不正常。我知道这与函数需要两个值这一事实有关,因为需要两个输入的其他计算器按钮(例如,执行置换计算的一个)表现出类似的行为。在执行电源功能后尝试将8除以2会使某些东西从墙上返回,例如35。

可能导致此行为的相关功能包括:

function checkNum(str) {
  for (var i = 0; i < str.length; i++) {
    var ch = str.substring(i, i + 1)
    if (ch < "0" || ch > "9") {
      if (ch != "/" && ch != "*" && ch != "+" && ch != "-" && ch != "." && ch != "(" && ch != ")" && ch != "%") {
      $('#disp').val("Error");
        return false
      }
    }
  }
  return true
}

function addChar(input, character) {
  if (input.value == null || input.value == "0"){
    input.value = character}
  else{
    input.value += character}
};

$.each([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], function(i, e) {
  $('#button-' + e).click(function() {
  if ($('#disp').hasClass("result")) {
      $('#disp').removeClass("result").val("");
    }
    addChar(this.form.display, e);
  });
});

计算器上只需要一个输入的其他按钮,例如余弦按钮,以这种方式使用JavaScript和jQuery:

function cos(form) {
    form.display.value = Math.cos(form.display.value);
}

$('#button-cos').click(function() {
  if (checkNum(this.form.display.value)) {
    cos(this.form);
    $('#disp').addClass("result");
  }
});

我想知道是否有可能让计算器显示类似2^5的内容并以某种方式解析它以执行Math.pow(2,5)?我认为这将解决问题。

这是计算器的小提琴:https://jsfiddle.net/Lh2x7vja/819/

为凌乱的剧本道歉 - 我还没有清理它!

0 个答案:

没有答案