繁体   English   中英

Window.prompt仅接受数值

[英]Window.prompt accept only numeric values

我正在尝试(虽然未成功)制作一个接受数值(0、1、2、3,...)的window.prompt,但我认为我做错了。 看我的功能。 我有误会吗? 我如何在我的代码中使用此正则表达式/^[0-9.,]+$/

<script>
    function save3() {
      var pn = 4; 
      do{
        var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10);
if (selection != (/^[0-9.,]+$/)){
    window.alert("xana");       
    }
        }while(isNaN(selection));
    $("#user_id").val(selection)
      //$("#user_id").val(prompt("Give the User Id:"))
      do{
        var selection2 = parseInt(window.prompt("Give the Book Id:", "Type a number!"), 10);
        }while(isNaN(selection2));
    $("#book_id").val(selection2)
      //$("#book_id").val(prompt("Give the Book Id:"))
      do{
        var selection3 = parseInt(window.prompt("Give the Game Id:", "Type a number!"), 10);
        }while(isNaN(selection3));
    $("#game_id").val(selection3)
      //$("#game_id").val(prompt("Give the Game Id:"))
      $("#site_id").val(pn)
    }
  </script>

您可以使用RegExp.test()来检查您的输入,例如:

const isInteger = /^(\d)+$/g;
if(isInteger.test(selection)) {
  console.log('Correct input!');
  // ... code
}

您应该将代码减少到再现该问题所需的最低限度,例如:

  var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10); if (selection != (/^[0-9.,]+$/)){ console.log('fail'); } else { console.log('pass'); } 

这将为任何值返回“失败”,因为您正在针对一个永远不能相等的正则表达式对象测试一个数字。

如果只希望用户输入数字,句点(。)和逗号(,),则将输入的文本保留为字符串,并使用测试方法对其进行测试 我也颠倒了测试,因此更有意义:

 var selection = parseInt(window.prompt("Give the User Id:", "Type a number!"), 10); if ( /^[0-9.,]+$/.test(selection)) { console.log('pass'); } else { console.log('fail'); } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM