Javascript文本输入计算器

时间:2013-04-14 00:44:12

标签: javascript html javascript-events

我对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>

6 个答案:

答案 0 :(得分:2)

我建议如下(代码本身评论的解释):

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;
    }
}

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

我建议使用eval() 如果用户输入&#34; 5 + 6&#34;或&#34;(9 * 3)/ 5&#34;并将其设置为变量,eval()将解析并解决问题!

答案 2 :(得分:0)

else if而不是elseif。你还需要在A + C上使用parseInt,否则它会将你的字符串视为......好吧,字符串。您应该已经在浏览器中看到了elseif错误。你使用像firebug这样的东西吗?如果你不是,那就开始吧。让工具为您努力工作。

答案 3 :(得分:0)

我会做的事情有所不同,但为了回答你的问题并让你的代码正常工作我做了以下事情:

这是您重写的代码:

<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>

我使用了parseint(),因为你的if语句中的表达式正在处理像text这样的值。

接下来我们需要使用===三个等于A等于+或者第二个输入值是什么。

第三个是onclick,我做了一个(这个)和反馈表单,你可以在行中看到函数calc。

为了好的措施,我添加了一个返回false;防止表单提交(但没有它就会运行)。

也像其他海报所说的那样,否则是否是其他。

我希望这会有所帮助。再说一遍,我会采取不同的做法,但让它得到一些解释。

答案 4 :(得分:0)

有一种方法可以通过一个输入框来实现:

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¡");
  }

}

答案 5 :(得分:-1)

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Amanpreet singh</title>
</head>
<body>
    <center>
<table  cellpadding="10" cellspacing="10" style="font-size:2em">
    <tr><td>Number 1:</td>
        <td><input type="text" id="num1" name="num1" /></td>
    </tr>
    <tr><td>Number 2:</td>
        <td> <input type="text" id="num2" name="num2" /></td>
    </tr>
    <tr>
        <td>  <label for=" Operator"> Operator:</label></td>
        <td> <select name="Operator" id="op" name="op">
    <option value="+">Add</option> <option value="-">Subtract</option>
    <option value="*">Muliply</option><option value="/">Divide</option>
  </select></td>
    </tr>
    <tr><td colspan="2" align="cover">
   <center> <input type="button" value="Solve" onclick="calc()" />
</center></td>
</tr>
<tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
</table></center>
<script type="text/javascript">
function calc() {
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 = "Result is :"+D;
return false;
}
</script>
</body>
</html>

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>Amanpreet singh</title>
    </head>
    <body>
        <center>
    <table  cellpadding="10" cellspacing="10" style="font-size:2em">
        <tr><td>Number 1:</td>
            <td><input type="text" id="num1" name="num1" /></td>
        </tr>
        <tr><td>Number 2:</td>
            <td> <input type="text" id="num2" name="num2" /></td>
        </tr>
        <tr>
            <td>  <label for=" Operator"> Operator:</label></td>
            <td> <select name="Operator" id="op" name="op">
        <option value="+">Add</option> <option value="-">Subtract</option>
        <option value="*">Muliply</option><option value="/">Divide</option>
      </select></td>
        </tr>
        <tr><td colspan="2" align="cover">
       <center> <input type="button" value="Solve" onclick="calc()" />
    </center></td>
    </tr>
    <tr><td colspan="2" style="text-align: center;"><p id="result" name="r1" ></p></td></tr>
    </table></center>
    <script type="text/javascript">
    function calc() {
    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 = "Result is :"+D;
    return false;
    }
    </script>
    </body>
    </html>