标签:type idt margin javascrip onload element target input for
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
input { width: 60px; }
div { margin: 10px 0 }
</style>
<script type="text/javascript">
window.onload = function () {
// 获取元素
var num1 = document.getElementById(‘num1‘);
var num2 = document.getElementById(‘num2‘);
var ret = document.getElementById(‘ret‘);
var btns = document.getElementsByTagName(‘button‘);
var p = parseInt;
//为按钮添加点击事件,计算结果
for(var i = 0;i<btns.length;i++){
btns[i].onclick=function(event){
//判断两个输入框不为空并且输入的是数字
if(!isNaN(p(num1.value))&&!isNaN(p(num2.value))){
var event = event.target || event.srcElement;
var how = event.innerText;
switch(how){
case "+":
ret.innerText = p(num1.value) + p(num2.value);
break;
case "-":
ret.innerText = p(num1.value) - p(num2.value);
break;
case "*":
ret.innerText = p(num1.value) * p(num2.value);
break;
case "/":
ret.innerText = p(num1.value) / p(num2.value);
break;
}
}else{
ret.innerText = "";
}
}
}
}
</script>
</head>
<body>
<input id="num1" type="text"/>
<input id="num2" type="text"/>
<div>结果:<span id="ret"></span></div>
<button>+</button>
<button>-</button>
<button>*</button>
<button>/</button>
</body>
</html>
标签:type idt margin javascrip onload element target input for
原文地址:https://www.cnblogs.com/aivnfjgj/p/12291602.html