这篇文章主要介绍了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>
感谢你能够认真阅读完这篇文章,希望小编分享的“JavaScript基于DOM操作如何实现数学运算功能”这篇文章对大家有帮助,同时也希望大家多多支持编程网,关注编程网行业资讯频道,更多相关知识等着你来学习!