如何使用Switch在Javascript中构建计算器?

时间:2015-02-08 03:43:40

标签: javascript html

HTML:

<div id="content">
      <div id="calculator-container">
        <form name="calc">
          <!-- The name of the form is "calc" -->
          <label for="output">A Basic Calculator</label>
          <input id="output" name="output" type="text" readonly>

          <!-- the name of the textbox is "output" -->
          <br>
          <input type="button"   name="one"      value="  1  "    >
          <input type="button"   name="two"      value="  2  "    >
          <input type="button"   name="three"    value="  3  "    >
          <input type="button"   name="add"      value="  +  "    >
          <br>
          <input type="button"   name="four"     value="  4  "    >
          <input type="button"   name="five"     value="  5  "    >
          <input type="button"   name="six"      value="  6  "    >
          <input type="button"   name="subtract" value="  -  "    >
          <br>
          <input type="button"   name="seven"    value="  7  "    >
          <input type="button"   name="eight"    value="  8  "    >
          <input type="button"   name="nine"     value="  9  "    >
          <input type="button"   name="multiply" value="  x  "    >
          <br>
          <input type="button"   name="clear"    value="  C  "    >
          <input type="button"   name="zero"     value="  0  "    >
          <input type="button"   name="equate"   value="  =  "    >
          <input type="button"   name="divide"   value="&divide;" >
        </form>
      </div>
      <h2>Switch Version</h2>
    </div>

它继续,老师正确设置了其他一切。不幸的是,不能发布图片。

JAVASCRIPT:

var calcu = function(calcValue) {
    switch (calcValue) {
        case "one": 
            calc.output.value += 1;
            break;
        case "equate":
            // use the math.eval() function from the Math.js math library to parse and evaluate the String with mathematics in it
            calc.output.value = math.eval(calc.output.value);
            break;
    }
};

所以根据我的理解,按下&#39; 1&#39;现在,计算器应该在输出格式中显示1。

我的老师为我们设置了在JS文件中使用的功能,所有内容都正确链接。我环顾了一下甚至是JS计算器代码,但我不确切地知道要问什么或如何问它。希望有人可以提供帮助。谢谢!

1 个答案:

答案 0 :(得分:1)

所以我已经弄明白了,感谢@claies。

HTML:

<input type="button"   name="one"      value="  1  "   onclick="calcu(this.name)" >

JavaScript的:

calc.output.value += "1";