练习:使用JS完成简易计算器
效果图:
<!DOCTYPE html>
<html>
<head>
<title> 事件</title>
<script type="text/javascript">
function count()
{
var num1 = document.getElementById("txt1").value;
var num2 = document.getElementById("txt2").value;
var sel = document.getElementById("select").value;
var a = parseInt(num1);
var b = parseInt(num2);
var num3;
switch(sel){
case "+":
num3 = a+b;
break;
case "-":
num3 = a-b;
break;
case "*":
num3 = a*b;
break;
case "/":
num3 = a/b;
break;
}
document.getElementById("x").value = num3;
}
</script>
</head>
<body>
<input type='text' id='txt1' />
<select id='select'>
<option value='+'>请选择</option>
<option value='+'>+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type='text' id='txt2' />
<input type='button' value='=' onclick="count()"/> <!--通过 = 按钮来调用创建的函数,得到结果-->
<input type='text' id="x" onblur="count()" />
</body>
</html>
onclick使其在被单击时触发,调用函数
onblur 事件会在对象失去焦点时发生。