<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>javascript检测是否为数字</title> </head> <script> window.onload = function() { var vals = document.getElementById("val"); var oBtn = document.getElementById("btns"); oBtn.onclick = function() { var num=detectNum(vals.value); if(num && !num=="") { alert("恭喜"+num+"全是数字") } else { alert("输入有误") } } function detectNum(str) { for(var i = 0; i < str.length; i++) { var n = 0; var n = str.charCodeAt(i) if(n < 48 || n > 57) { return false; } } return true; } //alert(detectNum(str)) } </script> <body> <input id="val" type="text"> <input id="btns" type="button" value="检测"> </body> </html>