Html Javascript 文本输入计算器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15994510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Text Input Calculator
提问by Brian Johnson
I am somewhat new to javascript and I'm trying to make a basic calculator that has 3 text inputs, a 1st number text box, an operation textbox, and a second number textbox, but it doesn't print out the text when I click a button or use any other method to trigger the event. This is my code:
我对 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>
回答by David says reinstate Monica
I'd suggest the following (explanations commented in the code itself):
我建议以下(代码本身中注释的解释):
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;
}
}
References:
参考:
回答by AndrewJ.G
I recommend using eval() If the user inputs "5+6" or "(9*3)/5" and you set that to a variable, eval() will parse and solve the problem!
我建议使用 eval() 如果用户输入“5+6”或“(9*3)/5”并且您将其设置为变量,则 eval() 将解析并解决问题!
回答by aquinas
It's else if
not elseif
. Also you need to use parseInt on A+C, otherwise it will treat your strings as...well, strings. You should have seen the elseif error in your browser. Are you using something like firebug? If you aren't, start. Let tools do the hard work for you.
这是else if
不是elseif
。您还需要在 A+C 上使用 parseInt,否则它会将您的字符串视为......好吧,字符串。您应该已经在浏览器中看到了 elseif 错误。你在用萤火虫之类的东西吗?如果你不是,那就开始吧。让工具为您完成繁重的工作。
回答by Frank Tudor
I would have done things a bit differently, but to answer your question and just get your code working I did the following:
我会做一些不同的事情,但是为了回答你的问题并让你的代码工作,我做了以下事情:
Here is your reworked code:
这是您重新设计的代码:
<html>
<script>
function calc(form) {
var D = "0";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = document.getElementById("num2").value;
if (B === "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B === "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B === "*")
{
D = parseInt(A)*parseInt(C);
}
else if (B === "/")
{
D = parseInt(A)/parseInt(C);
}
document.getElementById("result").innerHTML = D;
return false;
}
</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(this)">
<p id="result" name="r1">
<br />
</p>
</body>
</html>
I used the parseint() because your expressions in your if statements were treating values like text.
我使用 parseint() 是因为 if 语句中的表达式将值视为文本。
Next we need to use === Three equals which says A is really equal to + or what ever the second input value is.
接下来我们需要使用 === Three equals 表示 A 真的等于 + 或者第二个输入值是什么。
Third was the onclick, I did a (this) and feed back form as you can see in the line that says function calc.
第三个是 onclick,我做了一个(这个)并反馈表单,正如你在说函数 calc 的行中看到的。
For good measure I added a return false; to prevent form submission (but it will function without it).
为了更好地衡量,我添加了一个 return false ;防止表单提交(但没有它它也能运行)。
Also like other posters stated it is else if and not elseif.
也像其他海报所说的那样,它是 else if 而不是 elseif。
I hope this is helpful. Again, I would do things differently but got it working with some explanations.
我希望这是有帮助的。同样,我会以不同的方式做事,但通过一些解释让它起作用。
回答by Cris
There is a way you can do it with a single input box:
有一种方法可以使用单个输入框来完成:
function findOps(s) {
for (var i = 0; i < s.length; i++) {
if (s[i] == "+")
return "+";
if (s[i] == "-")
return "-";
if (s[i] == "*")
return "*";
if (s[i] == "/")
return "/";
}
}
var input = '';
function calc() {
var dom = $("#input");
input = dom.val();
try {
switch (findOps(input)) {
case "+":
var a = input.split("+");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x + y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "-":
var a = input.split("-");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x - y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "*":
var a = input.split("*");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x * y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
case "/":
var a = input.split("/");
var x = parseFloat(a[0]);
var y = parseFloat(a[1]);
var res = x / y;
if (!isNaN(res)) {
setTimeout(function() {
dom.val(res.toFixed(3));
dom.get(0).setSelectionRange(0, 0);
}, 150);
}
break;
}
} catch (err) {
alert("catched?");
}
}