javascript - 如何检查输入是否是数字并相应地调用函数?

标签 javascript html

我的代码如下。我需要对其进行修改,以便检查输入是否为数字。如果不是数字,则必须显示一条消息,如下所示“请仅输入编号”。 如果输入是数字,则必须调用函数compare()。我尝试了很多方法,包括使用isNAN,但似乎没有任何效果。有人可以帮忙吗?

<head>
<title>Guessing Game</title>
 <meta charset = "utf-8">
<script>
<!--

var num_guess=0;
function chkinput()
 {
  if (!isNaN(parseFloat(obj)) && isFinite(obj);) 
  {
compare();
  }
  else
   {

    alert("Please enter only numbers");
    return false;
   }
   }

function compare()
    {
 var generated_num = document.getElementById( "target" );
 var entered_num = document.getElementById( "userguess" );


    if ( parseInt( entered_num.value ) > generated_num.value )
   window.alert("Too high. Try again!");
  else if ( parseInt( entered_num.value ) < generated_num.value )
     window.alert("Too low. Try again!");
 else
  {
     window.alert("Congratulations!You guessed the number!");
  if ( parseInt( num_guess ) < 10 )
     window.alert( "Either you know the secret or"
 + " you got lucky!");
      if ( parseInt( num_guess ) == 10 )
   window.alert( "Ahah! You know the secret!" );
     if ( parseInt( num_guess ) > 10 )
   window.alert(
    "You should be able to do better!" );
    guess.userguess.value ="";
    window.status= "Done";


   random();

   } // end else
   num_guess++;
      } // end function compare

    function random() // function to generate a random no between 1 and 1000
    {
    document.getElementById( "target" ).value =
   Math.floor( 1 + Math.random() * 1000 );
   } // end function random
    // -->
  </script>
    </head>

   <body onload = "random()">
   <form id = "guess" action = "">
   <div>
   Guess a number between 1 and 1000:
  <input type = "text" id = "userguess" /><br />
    <input type = "button" value = "Guess"
   onclick = "chkinput()" />
    <input type = "hidden" id = "target" value = "0" />

   </div>
     </form>

最佳答案

你可以尝试这样:

if (!isNaN(parseFloat(obj)) && isFinite(obj);) 
  {
    compare();
  }
 else
  {

    alert("Please enter only numbers");
    return false;
  }

关于javascript - 如何检查输入是否是数字并相应地调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22139958/

相关文章:

html - 如何让 FireFox 了解 div 的正确高度?

javascript - 从代码中的其他地方调用 JQuery 事件作为函数...?

html - 使用 CSS 为移动设备固定背景图片

javascript - 字符串替换为 JSON 中未转义的大括号

javascript - 样式浏览器滚动条

javascript - 正则表达式不匹配

javascript - 如何在不让整个浏览器跳下的情况下转到可滚动div中的 anchor 标记?

javascript - 刷新后需要一个事件的子菜单(jquery Accordion 菜单)

javascript - 与选项元素同步按钮

javascript - 当 Canvas 的高度超过屏幕的高度时(当滚动条出现时),如何在 Canvas (JavaScript)上测试鼠标检测