現在、こちらの記事(参考ページ)をもとに、
Javascriptにて電卓の作成をしています。
しかしながら演算子が連続で押下できてしまいます。
それを阻止したく試行錯誤しましたが、上手く作用しません。
どう直したらいいのでしょうか。
HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script> <link rel="stylesheet" href="stylesheet.css"> <title>電卓</title> </head> <body> <form name="calculator"> <table> <tr> <td colspan="4"> <input type="text" class="display" name="display" value="" disabled> </td> </tr> <tr> <td><input type="button" value="7" onclick="get_calc(this)"></td> <td><input type="button" value="8" onclick="get_calc(this)"></td> <td><input type="button" value="9" onclick="get_calc(this)"></td> <td><input type="button" value="+" class="operator1" id="operator" onclick="get_calc(this)" disabled></td> </tr> <tr> <td><input type="button" value="4" onclick="get_calc(this)"></td> <td><input type="button" value="5" onclick="get_calc(this)"></td> <td><input type="button" value="6" onclick="get_calc(this)"></td> <td><input type="button" value="-" class="operator1" onclick="get_calc(this)"></td> </tr> <tr> <td><input type="button" value="1" onclick="get_calc(this)"></td> <td><input type="button" value="2" onclick="get_calc(this)"></td> <td><input type="button" value="3" onclick="get_calc(this)"></td> <td><input type="button" value="*" class="operator1" name="multi_btn" onclick="get_calc(this)"></td> </tr> <tr> <td><input type="button" value="0" onclick="get_calc(this)"></td> <td><input type="button" value="00" onclick="get_calc(this)"></td> <td><input type="button" value="." onclick="get_calc(this)"></td> <td><input type="button" value="/" class="operator1" name="div_btn" onclick="get_calc(this)"></td> </tr> <tr> <td colspan="2"><input type="button" value="AC" class="operator2" onclick="get_calc(this)"></td> <td colspan="2"><input type="button" value="=" class="operator2" onclick="get_calc(this)"></td> </tr> </table> </form> <script src="main.js"></script> </body> </html>
JS
function get_calc(btn) { if(btn.value == "=") { document.calculator.display.value = eval(document.calculator.display.value); } else if (btn.value == "AC") { document.calculator.display.value = ""; } else { document.calculator.display.value += btn.value; document.calculator.display.multi_btn.value = "*"; document.calculator.display.div_btn.value = "/"; } }
押されたボタンが演算子で、直前に入力されたのが演算子だったら
後者を前者と入れ替えるとか?
まだ回答がついていません
会員登録して回答してみよう