使用JS完成一个简单的计算器功能。实现2个输入框中输入整数后,点击第三个输入框能给出2个整数的加减乘除。
<!DOCTYPE html> <html> <head> <title> 事件</title> <script type="text/javascript"> function count(){ //alert("ss"); //获取第一个输入框的值 var a=document.getElementById("txt1").value; a=parseInt(a,10); //获取第二个输入框的值 var b=document.getElementById("txt2").value; b=parseInt(b,10); //获取选择框的值 var opra=document.getElementById("select").value; //document.write(opra); var ans=0; //获取通过下拉框来选择的值来改变加减乘除的运算法则 switch(opra) { case \'+\': ans=a+b;break; case \'-\': ans=a-b;break; case \'*\': ans=a*b;break; case \'/\': ans=a/b;break; default:break; } //设置结果输入框的值 document.getElementById("fruit").value=ans; //alert(ans); } </script> </head> <body> <input type=\'text\' id=\'txt1\' /> <select id=\'select\'> <option value=\'+\'>+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <input type=\'text\' id=\'txt2\' /> <input type=\'button\' value=\' = \' onclick="count()" /> <!--通过 = 按钮来调用创建的函数,得到结果--> <input type=\'text\' id=\'fruit\' /> </body> </html>