js计算器代码怎么写,通过弹窗显示

JavaScript021

js计算器代码怎么写,通过弹窗显示,第1张

js计算器代码,通过弹窗显示步骤如下。

1、js计算器代码编写html,实现计算器页面视图效果。

2、js计算器代码编写,实现点击输入数字和符号输出结果。

3、js计算器代码创建click1函数,判断flag的值,如果是true就定位到第一个输入框,如果是false就定位到第二个输入框,将点击传过来的值与输入框里面的字符串拼接到一起。

4、js计算器代码定义result函数,定位到两个输入框,取出其中的值并转成整数,定位到隐藏输入框,取出里面的符号,然后判断是什么符号,进行相应的运算,弹出运算结果。

function test(){

     var txt1 = document.getElementById("txt1"),

         txt2 = document.getElementById("txt2"),

         txt3 = document.getElementById("txt3"),

         opt  = document.getElementById("sel")

     txt3.value =  eval(txt1.value + opt.value + txt2.value)//eval函数可计算某个字符串,并执行其中的的js代码

} <input type="text" id="txt1" />

<select id="sel">

     <option value="+">+</option>

     <option value="-">-</option>

     <option value="*">*</option>

     <option value="/">/</option>

</select>

<input type="text" id="txt2" />

=

<input type="text" id="txt3" />

<input type="button" id="btn" value="计算" onclick="test()"/>

//html

<input type="text" id="num1" value="" />

    <select id="mySelect">

        <option value="+">+</option>

        <option value="-">-</option>

        <option value="*">*</option>

        <option value="/">/</option>

    </select>

    <input type="text" id="num2" value="" />

    <input type="button" id="jisuan" value="计算" />

//js

<script>

    var oTxt1 = document.getElementById('num1')

    var oTxt2 = document.getElementById('num2')

    var oSelect = document.getElementById('mySelect')

    var oBtn = document.getElementById('jisuan')

    oBtn.onclick=function(){

        switch(oSelect.value){

            case '+':

                alert(parseInt(oTxt1.value)+parseInt(oTxt2.value))

                break

            case '-':

                alert(parseInt(oTxt1.value)-parseInt(oTxt2.value))

                break

            case '*':

                alert(parseInt(oTxt1.value)*parseInt(oTxt2.value))

                break

            case '/':

                if(parseInt(oTxt2.value) !== 0){

                    alert(parseInt(oTxt1.value)/parseInt(oTxt2.value))

                }else{

                    alert('除数不能为0')

                }

                

                break

            default:

                alert('Bug!!!')

        }

    }

</script>