日期:2014-05-16  浏览次数:20401 次

jsp+javascrip的简单运算器
<body>
??? ??? <input type="text" name="num1" id="num1">
??? ??? <input type="radio" name="radio1" value="radio1" checked="checked">
??? ??? +
??? ??? <input type="radio" name="radio1" value="radio2">
??? ??? -
??? ??? <input type="text" name="num2" id="num2">
??? ??? =
??? ??? <input type="text" name="num3" id="num3">
??? ??? <input type="button" name="button1" id="button2" value="运算"
??? ??? ??? onclick="operation()">

??? </body>
文本显示后如下图
+ - =
?
点运算后显示如下图
+ - =


<script type="text/javascript">
??? function operation() {
???????? //获取填入表单的数值并转化成浮点数值;
??? ??? var num1 = parseFloat(document.getElementById("num1").value);
??? ??? var num2 = parseFloat(document.getElementById("num2").value);
??????? //获取num3的Id
??? ??? var num3 = document.getElementById("num3");
?????? //获取单选按钮的组的Id
??? ??? var radio = document.getElementsByName("radio1");
??? ??? var commend;
????? //遍历单选按钮判断哪个按钮被选中
??? ??? for ( var i = 0; i < radio.length; i++) {
??? ??? ??? if (radio[i].checked == true) {
??? ??? ??? ??? commend = radio[i].value;
??? ??? ??? ??? break;
??? ??? ??? }
??? ??? }
????? //判断填入的内容是否为数字
??? ??? if (num1 != null && num2 != null) {
??? ??? ?? if (isNaN(num1) || isNaN(num2)) {
?? ???? ??? ??? if (isNaN(num1)) {
?? ???? ??? ??? ??? alert("第一个输入框输入的不是数字或者没有输入数值");
?? ???? ??? ??? } else {
?? ???? ??? ??? ??? alert("第二个输入框输入的不是数字或者没有输入数值");
?? ???? ??? ??? }
//判断选中的单选框的属性,
??? ??? ??? } else if (commend == "radio1") {
??? ??? ??? ??? var num4 = num1 + num2;
??? ??? ??? ??? num3.value = num4;
??? ??? ??? } else if (commend == "radio2") {
??? ??? ??? ??? var num4 = num1 - num2;
??? ??? ??? ??? num3.value = num4;
??? ??? ??? }
??? ??? }
??? }
</script>