html中使用select option作为运算符的承接容器,输入值,选择不同运算符,计算结果。
文章地址 https://www.cnblogs.com/sandraryan/
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> <input type="number" id="num1"> <input type="number" id="num2"> <select name="" id="sel"> <option value="+">+</option> <option value="-">-</option> <option value="*">*</option> <option value="/">/</option> </select> <span>=</span> <input type="number" id="num3" disabled> <button id="btn">click</button>
<!--num1, num2 用于接受用户的数字值,select放置运算符,num3禁止用户输入,用于放置返回值,button绑定点击事件 -->
方法一: if else判断
<script> var num1 = document.getElementById("num1"); var num2 = document.getElementById("num2"); var num3 = document.getElementById("num3"); var sel = document.getElementById("sel");
//获取需要的元素 btn.onclick = function(){ var val1 = parseInt(num1.value); var val2 = parseInt(num2.value);
//获取num1 num2的值,并从string转为number类型 if(sel.value=="+"){ num3.value = val1 + val2; }else if(sel.value=="-"){ num3.value = val1 - val2; }else if(sel.value=="*"){ // console.log("a"); num3.value = val1 * val2; }else if(sel.value=="/"){ num3.value = val1 / val2; }else{ console.log("o");
//else输出我为了测试玩的,可以不写 }
//当sleect的value分别为各个运算符时,进行不同的运算,并把value给第三个input框 }
</script> </body> </html>
方法二:
switch语句
<script> var num1 = document.getElementById("num1"); var num2 = document.getElementById("num2"); var num3 = document.getElementById("num3"); var sel = document.getElementById("sel"); btn.onclick = function(){ var val1 = parseInt(num1.value); var val2 = parseInt(num2.value); switch(sel.value){ case "+": num3.value = val1 + val2; break; case "-": num3.value = val1 - val2; break; case "*": num3.value = val1 * val2; break; case "/": num3.value = val1 / val2; break; } }