Javascript计算器 - 在输入之前清空字段

时间:2017-10-24 15:33:55

标签: javascript calculator

我正在尝试使用JavaScript构建计算器



    var btn5 = document.getElementById('btn5');
	var btn2 = document.getElementById('btn2');
	var btn5multiply = document.getElementById('btn5multiply');
	var result = document.getElementById('result');
	var calInput = document.getElementById('calInput');
	var backSpace = document.getElementById('backSpace');
	var C = document.getElementById('C');
	var blank = "Please enter a number";

	btn5.addEventListener('click', runFunction5);
	btn2.addEventListener('click', runFunction2);
	multiply.addEventListener('click', multiplyFunction);
	result.addEventListener('click', resultFunction);
	backSpace.addEventListener('click', backSpaceFunction);
	C.addEventListener('click', clearFunction);

	function runFunction5() {

		if(calInput.value == blank) {
			calInput.value = "";
			calInput.value += btn5.value;
		} else {
			calInput.value += btn5.value;
		}
	}

	function runFunction2() {
		calInput.value += btn2.value;
	}

	function multiplyFunction() {
		calInput.value += multiply.value;
	}

	function resultFunction() {

		if(calInput.value == "") {
			calInput.value = blank;
		} else {
			var storeVal = calInput.value;
			var cal = eval(storeVal);
			calInput.value = cal;
		}
	}

	function backSpaceFunction() {
		var storeVal = calInput.value;
		calInput.value = storeVal.substr(0, storeVal.length - 1);
	}

	function clearFunction() {
		calInput.value = "";
	}

<body>
	<input id="calInput" type="text" disabled="true" value=""><br><br>
	<button id="backSpace"><-</button>
	<button id="btn5" value="5">5</button>
	<button id="btn2" value="2">2</button>
	<button id="multiply" value="*">X</button>
	<button id="result">=</button>
	<button id="C">C</button>
</body>
&#13;
&#13;
&#13;

。在我的代码中,如果有人按下=键,它会显示消息Please enter a number。现在我想出了在按下=键之后按下数字键然后将每个按下的按键附加到输入字段后首先清除字段的方法,但由于我必须为每个数字键分配该条件,所以代码输入太多,有没有更好的方法来实现这一目标?现在我只在按下5时添加了这个条件。

4 个答案:

答案 0 :(得分:0)

您可以确定当前点击的按钮的值,如下所示:

["btn2", "btn3"].forEach(id =>
  document
    .getElementById(id)
    .onclick = numberClickHandler
);

现在我们只需要将其分配给所有按钮,例如:

{{1}}

答案 1 :(得分:0)

HTML中的一点修改就可以解决您的问题。我建议你在输入中添加一个placeholder属性。一旦输入值存在,占位符将消失,当没有输入值时,占位符将重新出现。

有关占位符的更多信息:https://www.w3schools.com/tags/att_input_placeholder.asp

演示http://jsfiddle.net/lotusgodkk/GCu2D/2194/

<强> HTML

<input id="calInput" type="text" disabled="true" value="" placeholder="Please enter a number">
<br>
<br>
<button id="backSpace">>
</button>
<button id="btn5" value="5">5</button>
<button id="btn2" value="2">2</button>
<button id="multiply" value="*">X</button>
<button id="result">=</button>
<button id="C">C</button>

<强> JS

var btn5 = document.getElementById('btn5');
var btn2 = document.getElementById('btn2');
var btn5multiply = document.getElementById('btn5multiply');
var result = document.getElementById('result');
var calInput = document.getElementById('calInput');
var backSpace = document.getElementById('backSpace');
var C = document.getElementById('C');
var blank = "Please enter a number";

btn5.addEventListener('click', runFunction5);
btn2.addEventListener('click', runFunction2);
multiply.addEventListener('click', multiplyFunction);
result.addEventListener('click', resultFunction);
backSpace.addEventListener('click', backSpaceFunction);
C.addEventListener('click', clearFunction);

function runFunction5() {
  calInput.value += btn5.value;
}

function runFunction2() {
  calInput.value += btn2.value;
}

function multiplyFunction() {
  calInput.value += multiply.value;
}

function resultFunction() {
  var storeVal = calInput.value;
  var cal = eval(storeVal);
  calInput.value = cal;
}

function backSpaceFunction() {
  var storeVal = calInput.value;
  calInput.value = storeVal.substr(0, storeVal.length - 1);
}

function clearFunction() {
  calInput.value = "";
}

一旦你这样做,你就不必在每种情况下都添加这个条件。

答案 2 :(得分:0)

    var numericValues = document.getElementById('numericValue');
	var result = document.getElementById('result');
	var calInput = document.getElementById('calInput');
	var backSpace = document.getElementById('backSpace');
	var C = document.getElementById('C');
	var blank = "Please enter a number";

	numericValues.addEventListener('click', pushNumericValue);
	multiply.addEventListener('click', multiplyFunction);
	result.addEventListener('click', resultFunction);
	backSpace.addEventListener('click', backSpaceFunction);
	C.addEventListener('click', clearFunction);

	function pushNumericValue(event) {
        var btnTarget = event.target
		if(calInput.value == blank) {
			calInput.value = "";
			calInput.value += btnTarget.value;
		} else {
			calInput.value += btnTarget.value;
		}
	}

	function multiplyFunction() {
		calInput.value += multiply.value;
	}

	function resultFunction() {

		if(calInput.value == "") {
			calInput.value = blank;
		} else {
			var storeVal = calInput.value;
			var cal = eval(storeVal);
			calInput.value = cal;
		}
	}

	function backSpaceFunction() {
		var storeVal = calInput.value;
		calInput.value = storeVal.substr(0, storeVal.length - 1);
	}

	function clearFunction() {
		calInput.value = "";
	}
<body>
	<input id="calInput" type="text" disabled="true" value=""><br><br>
	<button id="backSpace"><-</button>
    <div id="numericValue">
	  <button id="btn5" value="1">1</button>
	  <button id="btn5" value="2">2</button>
	  <button id="btn5" value="3">3</button>
	  <button id="btn2" value="4">4</button>
    </div>
	<button id="multiply" value="*">X</button>
	<button id="result">=</button>
	<button id="C">C</button>
</body>

一种方法 使用事件委派而不是监听所有数值并执行特定操作。定义父 div ,其中包含所有数值的子项并通过event.target属性监听它,您可以获取其单击按钮的值

答案 3 :(得分:0)

您需要做的就是为click事件的每个按钮分配一个公共函数,在该处理程序中,您可以使用event.target确定实际点击了哪个按钮。

现在,根本不需要input字段。您无法直接从中获取任何输入,实际上您正在将其用作输出机制。由于您希望将它放在自己的行上,因此常规div是更好的UI选择。

接下来,只需通过元素的value属性处理作为按钮内容的文本,而不是获取按钮的.textContent。这将使HTML变得更加简单。

现在,您在代码中有eval()作为获取已构建并将其作为表达式运行的字符串的方式。应始终避免使用eval()。几乎没有需要它的用例。它在应用程序中打开了安全性和性能问题。这是一个有争议的话题,但在我看来,任何支持它的人都不了解eval()或JavaScript。它需要更多的代码,但你可以在没有它的情况下进行数学计算。

此示例回答了您的问题并演示了我的建议。我甚至将您的场景扩展到包括所有基本的数学运算符,但在准备好进行生产部署之前,还有更多需要刷新的内容。

&#13;
&#13;
// Get both number buttons in an array:
var btns = Array.prototype.slice.call(document.querySelectorAll(".number"));

// Get all operator buttons in an array:
var operators = Array.prototype.slice.call(document.querySelectorAll(".operator"));
var operator = null;  // Will store the last operator pressed

var result = document.getElementById('result');
var output = document.getElementById('output');
var back = document.getElementById('backspace');
var clear = document.getElementById('clear');
var blank = "Please enter a number";

// Loop over the buttons in the numbers array
btns.forEach(function(btn){
  // Assign an event handler to the button
  btn.addEventListener("click", btnFunction);
});

// Loop over the buttons in the operators array
operators.forEach(function(op){
  // Assign an event handler to the button
  op.addEventListener("click", 	function (evt) {
    operator = evt.target.textContent;   // Get the operator and store it
    output.textContent += operator;      // Display the operator in the expression    
  });
});

// Set up event handlers:
result.addEventListener("click", doMath);
clear.addEventListener("click", function() { output.textContent = ""; });
back.addEventListener("click", function(){
  output.textContent = output.textContent.substring(0, output.textContent.length - 1);
});

// All event handling functions are automatically passed
// a reference to the event that triggered the function
function btnFunction(evt) {
  // And that event object exposes the actual DOM object
  // that triggered the event via the target property
  if(output.textContent == blank) {
    output.textContent = evt.target.textContent;
  } else {
      output.textContent += evt.target.textContent;
  }
}

function doMath() {
  // Check for no math to do yet
  if(output.textContent === ""){
    output.textContent = blank;
  }

  // Break up the expression into an array with the operands serving to delimit the parts
  var operands = output.textContent.split(/[+-/*]/);

  // Do the math:
  switch (operator){
    case "+" :
      // Operands is an array, so we want to do the math with the two items in the array which
      // we get by passing indexes of 0 and 1 to the array.
      output.textContent += " = " + (parseInt(operands[0], 10) + parseInt(parseInt(operands[1], 10)));
      break;
    case "-" :
      output.textContent += " = " +  (parseInt(operands[0], 10) - parseInt(parseInt(operands[1], 10)));
      break;
    case "*" :
      output.textContent += " = " +  parseInt(operands[0], 10) * parseInt(parseInt(operands[1], 10));
      break;
    case "/" :
      output.textContent += " = " +  parseInt(operands[0], 10) / parseInt(parseInt(operands[1], 10));
      break;        
  }
}
&#13;
#output { height:1em; padding:3px; }
&#13;
<body>
  <!-- No need for an input element here. -->
	<div id="output"></div>
  
	<button id="backspace">&larr;</button>
	<button class="number">5</button>
	<button class="number">2</button>
	<button class="operator">+</button>
	<button class="operator">-</button>
	<button class="operator">*</button>
  <button class="operator">/</button>
	<button id="result">=</button>
	<button id="clear">C</button>
</body>
&#13;
&#13;
&#13;