JS 在 HTML 中做加减乘除


<script type="text/javascript">
function fun(t){
var fa = parseInt(document.getElementById('fa').value);
var fb = parseInt(document.getElementById('fb').value);
var fc = document.getElementById('fc');
if(isNaN(fa) || isNaN(fb)){
alert("输入错误,请重新输入");
return;
}
switch(t){
case 1:
fc.value = fa + fb;
break;
case 2:
fc.value = fa - fb;
break;
case 3:
fc.value = fa * fb;
break;
case 4:
fc.value = fa / fb;
break;
}
}
</script>
</head>
<body>
<input type="text" id="fa" value=""/>
<input type="text" id="fb" value=""/>
<input type="text" id="fc" value=""/>
<input type="button" value="+" onclick="fun(1);" />
<input type="button" value="-" onclick="fun(2);" />
<input type="button" value="x" onclick="fun(3);" />
<input type="button" value="/" onclick="fun(4);" />

HTML   计算器

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>计算器</title>
</head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$("button").click(function(){
var first = parseInt($("#first").val());//获取第一个数的值并转化为数字
var second = parseInt($("#second").val());//获取第二个数的值并转化为数字
var sum = 0;//定义结果值
var symbol = parseInt($("[type=radio]:checked").val());//获取符号的值
//通过对符号的判断计算结果
switch(symbol){
case 0:
sum = first + second;
break;
case 1:
sum = first - second;
break;
case 2:
sum = first * second;
break;
case 3:
sum = first / second;
break;
}
var arr = ['+','-','*','/'];//输出的符号
$("h2 span").text(first + arr[symbol] + second +" = " +sum);//把结果输出到结果栏中
})
})
</script>
<body>
<h1>计算器</h1>
<p>数字一:<input type="text" id="first" style="width: 40px;" /></p>
<p>
<label><input type="radio" name="symbol" value="0" checked="checked"/>+</label>
<label><input type="radio" name="symbol" value="1" />-</label>
<label><input type="radio" name="symbol" value="2" />*</label>
<label><input type="radio" name="symbol" value="3" />/</label>
</p>
<p>数字二:<input type="text" id="second" style="width: 40px;" /></p>
<p><button>计算</button></p>
<h2>结果:<span></span></h2>
</body>
</html>
上一篇:tensorflow lite的demo在android studio上环境搭建


下一篇:C#图解教程第一章 C#和.NET框架