不錯的一個用正則檢測輸入的字符是否為數字的代碼,也是一種并不常見的寫法
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
- <title>Untitled Document</title>
- </head>
- <body>
- <input type="text" id="myInput" value="" />
- <input type="button" value="確定" id="myButton" />
- </body>
- </html>
- <script language="JavaScript" type="text/javascript">
- function $(obj){
- return document.getElementById(obj);
- }
- function checkIsInteger(str)
- {
- //如果為空,則通過校驗
- if(str == "")
- return true;
- if(/^(/-?)(/d+)$/.test(str))
- return true;
- else
- return false;
- }
- String.prototype.trim = function()
- {
- return this.replace(/(^[/s]*)|([/s]*$)/g, "");
- }
- $("myButton").onclick=function(){
- if(checkIsInteger($("myInput").value.trim())){
- alert("成功");
- }else{
- alert("只能是數字");
- }
- }
- </script>
新聞熱點
疑難解答