带有单选按钮的简单 JS 计算器

Simple JS calculator with radio buttons

我找到了和我一样的题目,但是看完后我无法解决我的问题,所以我想用 JS 做一个简单的计算器,但我做不到,它一直什么都不做!我认为主要问题出在单选按钮上。

你能帮我吗,我知道这很容易,但我还是个初学者。 PS:我不要jquery!!!

<!DOCTYPE html>
<html>
<head>
    <title>Exercice1 | JS</title>
    <script>
        function calcul (op, v1, v2){
                if (document.f.op[1].cheked) alert(parseInt(v1.value) + parseInt(v2.value));
                if (document.f.op[2].cheked) alert(parseInt(v1.value) - parseInt(v2.value));
                if (document.f.op[3].cheked) alert(parseInt(v1.value) * parseInt(v2.value));
                if (document.f.op[4].cheked) alert(parseInt(v1.value) / parseInt(v2.value));
            }   
    </script>
</head>
<body>
    <form name ="f" method="POST" action="">
        <label for="v1">Var 1</label>
        <input type="text" name="v1" id="v1"></input>
        <br> <br>
        <label for="v2">Var 2</label>
        <input type="text" name="v2" id="v2"></input>
        <br><br>

        <input type="radio" name="op" value="1"></input>
        <label for="1">+</label>
        <br>
        <input type="radio" name="op" value="2"></input>
        <label for="2">-</label>
        <br>
        <input type="radio" name="op" value="3"></input>
        <label for="3">*</label>
        <br>
        <input type="radio" name="op" value="4"></input>
        <label for="4">/</label>
        <br>
        <input type="submit" onclick="calcul(op, v1, v2)" value="Calculate"></input>
        <input type="reset"></input>
    </form>
</body>

有几件事可以解决我的问题:

不要在您的 calcul 函数中传递 op、v1、v2,并将您的函数更改为 function calcul (),因为您已经使用了这三个 - (op, v1, v2) 来声明元素的名称 -在你的函数中仍然可以访问具有相同名称的变量

checked 不正确,它是 .checked

    function calcul (){
                    if (document.f.op[0].checked) alert(parseInt(v1.value) + parseInt(v2.value)); 
// you are accessing an array - so index starts with Zero
                    if (document.f.op[1].checked) alert(parseInt(v1.value) - parseInt(v2.value));
                    if (document.f.op[2].checked) alert(parseInt(v1.value) * parseInt(v2.value));
                    if (document.f.op[3].checked) alert(parseInt(v1.value) / parseInt(v2.value));
                }   

也改变这个:

onclick="calcul()"