JavaScript简易计算器
Posted 嘆世殘者——華帥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript简易计算器相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JS计算器</title> <link rel="stylesheet" href="http://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"> </head> <body style="margin:50px"> <div class="form-group"> <div class="col-sm-3"> <input type="text" id="sum1" class="form-control" placeholder="请输入第一个数"> </div> <div class="col-sm-2"> <select id="sign" class="form-control"> <option>加</option> <option>减</option> <option>乘</option> <option>除</option> <option>取余</option> </select> </div> <div class="col-sm-3"> <input type="text" id="sum2" placeholder="请输入第二个数" class="form-control"> </div> <div class="col-sm-1"> <button id="equal" class="btn btn-info" style="width:100%;" onclick="equals()">=</button> </div> <div class="col-sm-3"> <label id="count"class="form-control"></label> </div> </div> <script type="text/javascript"> var sum1; var sum2; var sign; var fruit; function equals(){ sum1 = parseInt(document.getElementById("sum1").value); sum2 = parseInt(document.getElementById("sum2").value); if (isNaN(sum1) || isNaN(sum2)) { document.getElementById("count").innerHTML = "您输入的不是数字,请重新输入!"; }else{ sign = document.getElementById("sign").value; switch(sign){ case ‘加‘: fruit = sum1 + sum2; break; case ‘减‘: fruit = sum1 - sum2; break; case ‘乘‘: fruit = sum1 * sum2; break; case ‘除‘: if (sum2 == 0) { fruit = "被除数不能为0,请重新输入!"; break; }else{ fruit = sum1 / sum2; break; } case ‘取余‘: fruit = sum1 % sum2; break; } document.getElementById("count").innerHTML = fruit; }; } </script> </body> </html>
以上是关于JavaScript简易计算器的主要内容,如果未能解决你的问题,请参考以下文章