Javascript DOM Create Calculator 4
<!DOCTYPE html> <html> <head> <style type="text/css"> td {/*from ww w.j a v a2s. co m*/ border: 1px solid gray; width: 50px; } #results { height: 20px; } </style> </head> <body> <table border="0" cellpadding="2" cellspacing="2"> <tr> <td colspan="4" id="results"></td> </tr> <tr> <td><a href="#">1</a></td> <td><a href="#">2</a></td> <td><a href="#">3</a></td> <td><a href="#">+</a></td> </tr> <tr> <td><a href="#">4</a></td> <td><a href="#">5</a></td> <td><a href="#">6</a></td> <td><a href="#">-</a></td> </tr> <tr> <td><a href="#">7</a></td> <td><a href="#">8</a></td> <td><a href="#">9</a></td> <td><a href="#">*</a></td> </tr> <tr> <td><a href="#">Clear</a></td> <td><a href="#">0</a></td> <td><a href="#">=</a></td> <td><a href="#">/</a></td> </tr> </table> <script type="text/javascript"> function addDigit(digit) { let resultField = document.getElementById("results"); resultField.innerHTML += digit; } function calculate() { let resultField = document.getElementById("results"); resultField.innerHTML = eval(resultField.innerHTML); } function reset() { let resultField = document.getElementById("results"); resultField.innerHTML = ""; } function getHandlerFunction(innerHTML) { return function() { addDigit(innerHTML); }; } onload = function() { let links = document.getElementsByTagName("a"); let length = links.length; for (let i = 0; i < length; i++) { let link = links[i]; let innerHTML = link.innerHTML; let func = null; switch(innerHTML) { case "Clear": func = reset; break; case "=": func = calculate break; default: func = getHandlerFunction(innerHTML); break; } link.addEventListener("click", func, false); } }; </script> </body> </html>