我对 Javascript 有点陌生,我正在尝试制作一个基本的计算器,它有 3 个文本输入、第一个数字文本框、一个操作文本框和第二个数字文本框,但它不会打印出文本当我单击按钮或使用任何其他方法触发事件时。 这是我的代码:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if(B == "+")
{
D = A+C;
}
elseif(B == "-")
{
D = A-C;
}
elseif(B == "*")
{
D = A*C;
}
elseif(B == "/")
{
D = A/C;
}
document.getElementById("result").innerHTML = D;
}
</script>
<body>
<input type="text" id="num1" name="num1" />
<input type="text" id="op" name="op" />
<input type="text" id="num2" name="num2" />
<br />
<input type="button" value="Solve" onclick="calc()" />
<p id="result" name="r1">
<br />
</p>
</body>
</html>
最佳答案
我建议如下(代码本身注释的解释):
function calc() {
/* finds out whether the browser uses textContent (Webkit, Opera, Mozilla...)
or innerText (Microsoft) to set the text of an element/node */
var textType = Node.textContent ? 'textContent' : 'innerText',
/* uses parseFloat to create numbers (where possible) from the entered value
if parseFloat fails to find a number (it's empty or nonsensical)
then a 0 is used instead (to prevent NaN being the output). */
num1 = parseFloat(document.getElementById('num1').value) || 0,
num2 = parseFloat(document.getElementById('num2').value) || 0,
// retrieves the result element
result = document.getElementById('result');
// switch is used to avoid lots of 'if'/'else if' statements,
// .replace() is used to remove leading, and trailing, whitespace
// could use .trim() instead, but that'd need a shim for (older?) IE
switch (document.getElementById('op').value.replace(/\s/g,'')){
// if the entered value is:
// a '+' then we set the result element's text to the sum
case '+':
result[textType] = num1 + num2;
break;
// and so on...
case '-':
result[textType] = num1 - num2;
break;
case '*':
result[textType] = num1 * num2;
break;
case '/':
result[textType] = num1 / num2;
break;
// because people are going to try, give a default message if a non-math
// operand is used
default:
result[textType] = 'Seriously? You wanted to try math with that operand? Now stop being silly.'
break;
}
}
引用资料:
关于Javascript 文本输入计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15994510/