JavaScript:制作简易计算器要注意的事项!

<!DOCTYPE html>

<!--getElementById('idName'),是通过元素中的id名字来获取,而不是name,一定要注意-->

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <form action="" method="get" name="">
        <input type="text" name="txt_1" id="txt_1"/>
        
        <select name="" id="sel">                 <!--注意这个里面一定要有id,否则是获取不到的-->
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
        </select>
        
        <input type="text" name="txt_2" id="txt_2"/>
        <input type="button" value="=" onclick="compute()"/> 
        <input type="text" name="res" id = "res"/>
    </form>
    <script type="text/javascript">
        function compute(){
            var a=document.getElementById('txt_1').value;    //document.getElementById('txt_1')表示的是通过这个id获取当前的文本对象,value是它的一个属性
            var b=document.getElementById('txt_2').value;  
            var c=document.getElementById('sel').value;  
          

    <>

     switch(c){
                case '+': document.getElementById('res').value = parseInt(a)+parseInt(b); break; //pareInt(arg0) 将字符串转化成整数函数
                case '-': document.getElementById('res').value = parseInt(a)-parseInt(b); break;
                case '*': document.getElementById('res').value = parseInt(a)*parseInt(b); break;
                case '/': document.getElementById('res').value = parseInt(a)/parseInt(b); break;
                default:alert('error'); break;
            }
            
        }
    </script>
    </body>
</html>

原文地址:https://www.cnblogs.com/py1994/p/5993926.html