方法一:复杂方法,新手可能更好理解
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>加减乘除</title>
<style>
/* 设置样式:设为鼠标移到内容上为手的形状 (看个人习惯,加不加都行)* /
span{cursor:pointer;}
</style>
</head>
<body>
<input type="text" id='txt1'> 、 /* 给文本框设id,方便script声明 */
<select name="" id="s" value=''>
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" id='txt2'>
<span id='res'>=</span>
<input type="text" id='txt3'>
</body>
<script>
var txt1 = document.getElementById('txt1');
var txt2 = document.getElementById('txt2');
var txt3 = document.getElementById('txt3');
var s = document.getElementById('s');
res.onclick = function(){
var t1 = txt1.value; /* txt.value 赋值给 t1,目的是让书写更方便简洁点 */
var t2 = txt2.value;
var y = s.value;
console.log(t1,t2,y);
if(t1 == ''|| t2 == ''){ /* 当 t1 或 t2 没有输入数字时弹出警示框 */
alert('内容不能为空');
}else{
var re1 = parseFloat(t1);
var re2 = parseFloat(t2);
console.log(re1,re2);
if(isNaN(re1)||isNaN(re2)){ /* 当输入的文本是 非数字 ,弹出警示框 */
alert('请输入数字');
}else if(y == "+"){
txt3.value = re1 + re2;
txt1.value = ''; /* 作用: 结果显示出来时,前两个文本框内容为 空 */
txt2.value = '';
}else if(y == '-'){
txt3.value = re1 - re2;
txt1.value = '';
txt2.value = '';
}else if(y == '*'){
txt3.value = re1 * re2;
txt1.value = '';
txt2.value = '';
}else if(y == '/'){
txt3.value = re1 / re2;
txt1.value = '';
txt2.value = '';
}
}
}
</script>
</html>
方法二:更简洁
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" id='txt1'>
<select name="" id="sel">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id='txt2'>
<input type="button" value='=' id='btn'>
<input type="text" id='result'>
</body>
<script>
var txt1 = document.getElementById('txt1');
var sel = document.getElementById('sel');
var txt2 = document.getElementById('txt2');
var btn = document.getElementById('btn');
var result = document.getElementById('result');
btn.onclick = function(){
var t1 = txt1.value;
var t2 = txt2.value;
console.log(t1,t2);
if(t1 == '' || t2 == ''){
alert('请输入数字');
}else{
var n1 = parseFloat(t1);
var n2 = parseFloat(t2);
var m = sel.value //结果
console.log(n1,n2,m);
console.log(n1+m+n2); //5+'*'+7
result.value = n1 + m + n2 ;
result.value = eval(n1 + m + n2); /* eval表示把字符串转换成数字进行运算 */
}
}
</script>
</html>