0

我只想在键入除数字以外的键时取消 keydown 事件,

为此,我做了以下事情:

function handleNum(obj){
    var e = window.event;
    var flag = true;

    if( ( e.keyCode >=  48 && e.keyCode <=  57 ) ||          
            ( e.keyCode >=  96 && e.keyCode <= 105 ) ||   
        e.keyCode ==   8 ||  
        e.keyCode ==  46 ||  
        //e.keyCode == 110 ||
        //e.keyCode == 190 ||
        e.keyCode ==  37 ||  
        e.keyCode ==  39 ||  
        e.keyCode ==  35 ||  
        e.keyCode ==  36 ||  
        e.keyCode ==   9     
    ) {
        flag = true;
    } else { 
        alert('You can type only a number!');
        console.log("doesn't return?");
                    e.preventDefault();
        flag = false;
    }
    console.log(flag);
    return flag;
}

html:

   <input type="text" onkeydown="return handleNum(this);" />

但它不起作用,我该如何解决这个问题?我不知道为什么 e.preventDefault() 在任何浏览器中都不起作用。

4

2 回答 2

2

事件未定义,你可以这样传递

<script>
function handleNum(e,obj){
    if (!e) var e = window.event;

    var flag = true;

    if( ( e.keyCode >=  48 && e.keyCode <=  57 ) ||          
            ( e.keyCode >=  96 && e.keyCode <= 105 ) ||   
        e.keyCode ==   8 ||  
        e.keyCode ==  46 ||  
        //e.keyCode == 110 ||
        //e.keyCode == 190 ||
        e.keyCode ==  37 ||  
        e.keyCode ==  39 ||  
        e.keyCode ==  35 ||  
        e.keyCode ==  36 ||  
        e.keyCode ==   9     
    ) {
        flag = true;
    } else { 
        alert('You can type only a number!');
        console.log("doesn't return?");
        e.preventDefault();
        flag = false;
        obj.value = obj.value.replace(/\D/g, '');
    }
    console.log(flag);
    return flag;
}
</script>

<input type="text" onKeyDown="return handleNum(event,this);" />

小提琴

于 2013-05-24T05:50:39.113 回答
1

Here is a code that will return false if the key pressed is not a number.

Use the keypress event instead of keydown.

$(fieldid).keypress(function(e) {
    if (e.which != 8 && e.which != 0 && (e.which<48 || e.which>57)) {
        return false;
    }
});
于 2013-05-24T05:48:59.057 回答