简体   繁体   English

为什么javascript功能不起作用?

[英]Why javascript function not working ?

I was using this function to enter only digits in to textbox and it worked. 我正在使用此功能只输入文本框中的数字并且它有效。

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

but customer asked me to restrict - sign so user should not enter - sign. 但是客户要求我限制-签名,这样用户就不应该输入 - 签名。 So i modified the code to this 所以我修改了代码

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode == 45)
        return false;

    return true;
}

and now it not works, it allows letters too, why ? 现在它不起作用,它也允许字母,为什么?

You need || 你需要|| in the group: 在小组中:

 function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; var bool = (charCode > 31) && (charCode < 48 || charCode > 57 || String.fromCharCode(charCode) == "-"); return !bool; } 
 <input type="text" onkeypress='return isNumberKey(event)'> 

You should use || 你应该使用|| instead of && in your test. 而不是在你的测试中的&&
On my azerty keyboard, the - sign charcode is 54 , not 45 . 在我的azerty键盘上, - sign charcode是54 ,而不是45

function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode == 45) )
        return false;

    return true;
}

See this fiddle 看到这个小提琴

Edit 编辑

Looks like your charCode is correct . 看起来你的charCode 是正确的 The 54 value comes from my azerty keyboard. 54值来自我的azerty键盘。
Nevertheless, you should use || 不过,你应该使用|| instead of && in your check. 而不是&&在您的支票。

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

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