JavaScript基于DOM操作实现简单的数学运算功能示例
本文实例讲述了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.jb51.net/jisuanqi/equ_jisuanqi
科学计算器在线使用_高级计算器在线计算:
http://tools.jb51.net/jisuanqi/jsqkexue
在线计算器_标准计算器:
http://tools.jb51.net/jisuanqi/jsq
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript操作DOM技巧总结》、《JavaScript替换操作技巧总结》、《javascript编码操作技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。
相关推荐
zrtlin 2020-11-09
xuebingnan 2020-11-05
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
softwear 2020-08-21
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17