JavaScript用if..else设立计算公式问题点求解

刚开始学编程,下面是我编写代码遇到的问题。

<button type="button" onclick="operation()">计算</button>

这段代码运行后的点击按钮无法执行。

<body>
        <script type="text/javascript">
            //输入数字1选择运算符输入数字2点击计算得出正确的结果并填充到结果文本框中
            function operation() 
            {
                var n1 = document.getElementById('num1');
                var n2 = document.getElementById('num2');
                var n3 = document.getElementById('num3');
                if(sym.value == '+'){
                    n3.value = parseInt(n1) + parseInt(n2);
                } else if(sym.value == '-') {
                    n3.value = parseInt(n1) - parseInt(n2);
                } else if(sym.value == '*') {
                    n3.value = parseInt(n1) * parseInt(n2);
                } else if(sym.value == '/'&&num_2!=0) {
                    n3.value = parseInt(n1) / parseInt(n2);
                } else if(sym.value == '%'&&num_2!=0) {
                    n3.value = parseInt(n1) % parseInt(n2);
                }
            }
        </script>
        数字1:<input type="text" id="num1" />
        <select id="sym">
            <option value="+">+</option>
            <option value="-">-</option>
            <option value="*">*</option>
            <option value="/">/</option>
            <option value="%">%</option>
        </select>
        数字2:<input type="text" id="num2" /> =结果:
        <input type="text" id="num3 " />
        <button type="button" onclick="operation()">计算</button>
    </body>

麻烦帮忙看下哪里出了问题呢。

第一点:你的n3的id后面多了一个空格,获取不到n3的input标签
第二点:获取input框内容的方法是 n1.value 你的代码应该改成这样 n3.value = parseInt(n1.value) + parseInt(n2.value);

别看哪里的问题了,我这里刚好有个

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>less01</title>
</head>

<body>


    请输入第一个数:<input type="text" id="num1"><br/>
    <select name="" id="qw">
        <option value="1">+</option>
        <option value="2">-</option>
        <option value="3">*</option>
        <option value="4">/</option>
    </select>
    <br/>
    请输入第二个数:<input type="text" id="num2"><br/>

    <button onclick="fun()">计算</button><br>

    得出结果:<label id="txt"></label><br>

</body>
<script>
    function fun() {
        num1 = Number(document.getElementById("num1").value);
        num2 = Number(document.getElementById("num2").value);
        qw = document.getElementById("qw").value;
        if (qw == 1) {
            res = num1 + num2;
        }
        if (qw == 2) {
            res = num1 - num2;
        }
        if (qw == 3) {
            res = num1 * num2;
        }
        if (qw == 4) {
            res = num1 / num2;
        }

        document.getElementById("txt").innerText=res;

    }
</script>

</html>
···
效果:

![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/29152950435612.png "#left")

少定义了一个sym
var sym = document.getElementById('sym')

你刚学的话我建议你自己学会调试,每次执行的时候你按f12打开控制台,有报错的话console会有提示的,要自己学会调试

img