JS处理的一般步骤:
1、先获取元素的对象
2、再通过元素的属性取到相应的值
3、用户输入的数字是字符串,还需要将其转为数值型
<script type="text/javascript"> function computing(){ var firstObj = window.document.getElementById("firstNum"); //先获取元素的对象 var firstVal = parseFloat(firstObj.value); //再获取元素的值 var secondObj = window.document.getElementById("secondNum"); var secondVal = parseFloat(secondObj.value); var sign = window.document.getElementById("sign"); var results = window.document.getElementById("results"); var res = 0; switch(sign.value){ //sign 是对象 case "+": res = firstVal + secondVal; break; case "-": res = firstVal - secondVal; break; case "*": res = firstVal * secondVal; break; case "/": res = firstVal / secondVal; } results.value =res.toFixed(2); } </script> <body> firstNum:<input type="text" name="firstNum" value="1" id="firstNum"><br> secondNum:<input type="text" name="secondNum" value="2" id="secondNum"><br> <select name="signName" id="sign"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <br> <input type="button" value="=" onclick="computing()"><br> results:<input type="text" name="results" id="results"><br> </body>
原文:https://www.cnblogs.com/luoxuw/p/11033164.html