用Visual Studio Code写一个计算器

功能:实现简单的加减乘除

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" name="" id="num1" value="">
    <select name="" id="op">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
    </select>
    <input type="text" name="" id="num2" value="">
    <input type="button" value="计算" onclick="calc()">
    <input type="text" name="" id="num3" value="">
</body>
</html>
    <script>
        function calc(){
            let num1Obj = document.getElementById("num1");
            let num1 = num1Obj.value;
            console.log(num1);
            let num2Obj = document.getElementById("num2");
            let num2 = num2Obj.value;
            console.log(num2);

            if(num1 == "" || num2 == ""){
                alert("数据不合法");
                return;
            }

            if(window.isNaN(num1) || window.isNaN(num2)){
                alert("数据不合法");
                return;
            }

            let opObj = document.getElementById("op");
            let op = opObj.value;
            console.log(op);
            let num3;
            if(op == "+"){
                num3 = window.parseInt(num1) + window.parseInt(num2);
            }else if (op == "-"){
                num3 = window.parseInt(num1) - window.parseInt(num2);
            }else if (op == "*"){
                num3 = window.parseInt(num1) * window.parseInt(num2);
            }else{
                num3 = window.parseInt(num1) / window.parseInt(num2);
            }
            let num3Obj = document.getElementById("num3");
            num3Obj.value = num3;
        }
    </script>

页面展示:
用Visual Studio Code写一个计算器_第1张图片

结果演示:
1.
用Visual Studio Code写一个计算器_第2张图片
2.
用Visual Studio Code写一个计算器_第3张图片
3.
用Visual Studio Code写一个计算器_第4张图片

用Visual Studio Code写一个计算器_第5张图片

你可能感兴趣的:(Java实训日记,javascript,前端,html)