实现代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{margin: 0px;padding: 0px;} body{padding: 100px;} input[type=text]{width: 50px;background-color: #eee;border: 1px solid #ccc;height: 26px;line-height: 26px;} span{display: inline-block;width: 30px;} input[type=button]{padding: 5px 10px;} </style> <script> window.onload=function(){ var aInput = document.getElementsByTagName('input'); var oSpan = document.getElementsByTagName('span')[0]; var oBtn = document.getElementById('btn'); for(var i=0;i<aInput.length-1;i++){ aInput[i].onkeyup=function(){ this.value = this.value.replace(/[^d]/,'') } } oBtn.onclick=function(){ (aInput[0].value==""||aInput[1].value=="")? alert('请输入数字'):oSpan.innerHTML=parseInt(aInput[0].value)+parseInt(aInput[1].value); } } </script> </head> <body> <input type="text" /> + <input type="text" /> = <span></span> <input id="btn" type="button" value="求和" /> </body> </html>
这里有用到正则表达式判断输入是否为数字。
结果如下图所示: