用Javascript写简单的加减乘除运算:
<html>
<head>
<title>runcode</title>
<script type = "text/javascript">
function run(t){
var sa = parseInt(document.getElementById('sa').value);
var sb = parseInt(document.getElementById('sb').value);
var sc = document.getElementById('sc');
if(isNaN(sa) || isNaN(sb)){
alert("输入错误,请重新输入!");
return;
}
switch(t){
case 1 :
sc.value = sa + sb;
break;
case 2 :
sc.value = sa - sb;
break;
case 3 :
sc.value = sa * sb;
break;
case 4 :
if(sb == 0){
alert("被除数不能为0!");
return;
}
sc.value = sa / sb;
break;
}
}
</script>
</head>
<body>
<input type = "text" id = "sa" value = "请输入第一个数字.... " onclick = "this.value =''"/><br/><br/>
<input type = "text" id = "sb" value = "请输入第二个数字.... " onclick = "this.value =''"/><br/><br/>
<input type = "button" value = " + " onclick = "run(1)" />
<input type = "button" value = " - " onclick = "run(2)" />
<input type = "button" value = " * " onclick = "run(3)" />
<input type = "button" value = " / " onclick = "run(4)" /><br/><br/>
<input type = "text" id = "sc" value = "显示结果...."/>
</body>
</html>
本文介绍如何使用JavaScript实现加减乘除四种基本数学运算,包括输入验证和错误处理。
3678

被折叠的 条评论
为什么被折叠?



