题目
给button按钮绑定一个点击事件, 在点击button按钮时计算等号左边的值的和并且把值给到等号右边
思路:
1.给button按钮添加事件绑定函数
2.获取等号左边的值
3.把等号左边的值的和赋给等号右边
代码如下(示例):
<body>
<input id="first" type="text">
+
<input id="second"type="text">
<button id="btn">=</button>
<input id="result" type="text" disabled>
</body>
<script>
//简单的点击事件
btn.onclick = function () {
console.log('我点击了button按钮')
var a = first.value - 0;
var b = second.value - 0;
var res = a + b;
result.value = res;
}
</script>
题目
和上面一样, 只不过加号换成四则运算
代码如下(示例):
<body>
<form action="">
<input type="text" id="first">
<select name="" id="type">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" id="second">
<!-- button标签在form里面相当于submit, 等价于 input type = "submit" -->
<!-- 解决办法: 设置button按钮的type为button -->
<button id="btn" type="button">=</button>
<input type="text" disabled id="result">
</form>
</body>
<script>
btn.onclick =function (){
var a = first.value - 0;
var b = second.value - 0;
var t = type.value;
var res;
switch(t){
case "+": res = a + b; break;
case "-": res = a - b; break;
case "*": res = a * b; break;
case "/": res = a / b; break;
}
result.value = res;
}
</script>