Posted in Javascript onJanuary 16, 2017
本文实例讲述了JavaScript基于DOM操作实现简单的数学运算功能。分享给大家供大家参考,具体如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8"> <title>简单的DOM操作-实现简单的运算</title> <script type="text/javascript" language="javascript"> window.onload = function () { //alert("window.onload!!!"); var opNum1 = window.document.getElementById("opNum1"); var opNum2 = window.document.getElementById("opNum2"); //var op = window.document.getElementById("op"); var btnElements = window.document.getElementsByName("operater"); //.getElementsByTagName("input[type=button]"); var btnElementsLength = btnElements.length; for (var i = 0; i < btnElementsLength; i++) { //alert(i); btnElements[i].onclick = function () { //alert(opNum1.value + "_" + opNum2.value + "_" + this.value); operate(opNum1.value, opNum2.value, this.value); } } } function operate(opNum1, opNum2, op) { var result=null; switch (op) { case "+": result = parseFloat(opNum1) + parseFloat(opNum2); break; case "-": result = parseFloat(opNum1) - parseFloat(opNum2); break; case "*": result = parseFloat(opNum1) * parseFloat(opNum2); break; case "/": result = parseFloat(opNum1) / parseFloat(opNum2); break; case "%": result = parseFloat(opNum1) % parseFloat(opNum2); break; default: break; } var resultElement = window.document.getElementById("resultSpan"); resultElement.innerHTML = result; } </script> <style type="text/css"> body{ line-height:30px; font-size:20px; } input[type=button]{ width:50px; } </style> </head> <body> 运算数1:<input type="text" id="opNum1" /><br /> 运算数2:<input type="text" id="opNum2" /><br /> 选择操作符: <input type="button" name="operater" value="+" /> <input type="button" name="operater" value="-" /> <input type="button" name="operater" value="*" /> <input type="button" name="operater" value="/" /> <input type="button" name="operater" value="%" /> <br /> 运算结果为:<span id="resultSpan"></span><br /> </body> </html>
PS:这里再为大家推荐几款计算工具供大家进一步参考借鉴:
在线一元函数(方程)求解计算工具:
http://tools.3water.com/jisuanqi/equ_jisuanqi
科学计算器在线使用_高级计算器在线计算:
http://tools.3water.com/jisuanqi/jsqkexue
在线计算器_标准计算器:
http://tools.3water.com/jisuanqi/jsq
希望本文所述对大家JavaScript程序设计有所帮助。
JavaScript基于DOM操作实现简单的数学运算功能示例
- Author -
lx_3278@126声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@