为什么先把 两个变量 定义好 其结果会变成NAN呢?
<!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 x = parseInt(num1.value); var y = parseInt(num2.value); btns[0].onclick = function(){ ret.innerHTML =(x+y); } btns[1].onclick = function(){ ret.innerHTML =(x-y); } btns[2].onclick = function(){ ret.innerHTML =(x*y); } btns[3].onclick = function(){ ret.innerHTML =(x/y); } } </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>