1

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

6 回答 6

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 小提琴演示

参考:

于 2013-04-14T01:12:11.777 回答
1

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

这是您重新编写的代码:

<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 语句中的表达式将值视为文本。

接下来我们需要使用 === 三个等号,它表示 A 真的等于 + 或者第二个输入值是什么。

第三个是 onclick,我做了一个 (this) 并反馈表单,正如你在函数 calc 行中看到的那样。

为了更好地衡量,我添加了一个 return false; 防止表单提交(但没有它它会起作用)。

也像其他海报所说的那样,它是 else if 而不是 elseif。

我希望这是有帮助的。同样,我会以不同的方式做事,但可以通过一些解释来解决。

于 2013-04-14T01:49:47.807 回答
1

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

于 2017-05-10T20:00:45.067 回答
0

else if不是elseif。_ 您还需要在 A+C 上使用 parseInt,否则它会将您的字符串视为......以及字符串。您应该已经在浏览器中看到 elseif 错误。你在用萤火虫之类的东西吗?如果你不是,开始吧。让工具为您完成繁重的工作。

于 2013-04-14T00:50:14.647 回答
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¡");
  }

}
于 2016-05-17T03:44:18.403 回答
-2
<!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>
于 2021-06-11T09:42:20.660 回答