更改按下的键的charCode

时间:2012-02-19 09:33:32

标签: javascript jquery events keypress

在下面的示例中,我尝试更改按下的键的charCode,但它不会更改。当我按“a”时,我希望它输入“b”。我做错了什么?

$("#target").keypress(function(event) {
     if ( event.which == 97 ) {
         //alert('pressed a');
         //event.preventDefault();
         event.keyCode = 98;
         event.charCode = 98;
         event.which = 98;
     }
});

2 个答案:

答案 0 :(得分:3)

您无法覆盖事件对象中的键码...

请看这个片段:

$('#target').keypress(function(e){
    if (e.which == 97)
        this.value = this.value + String.fromCharCode(98)
    else
        this.value = this.value + String.fromCharCode(e.which)

    ....

    return false;
})

答案 1 :(得分:0)

将逗号和短划线替换为斜线。

$('.pdate').on('keypress', function (e) {
        var ch = String.fromCharCode(e.keyCode);
        $("div").text(e.keyCode)
        if (!((ch >= '0' && ch <= '9') || 
        ch == '/' || ch == ',' || ch == '-')) {
            return false;
        }
        if (ch == ',' || ch == '-')
        {
            var val = $(this).val();
            var s = this.selectionStart;
            val = val.slice(0, s) + "/" + val.slice(s, val.length);
            $(this).val(val)
            this.selectionStart = s +1;
            this.selectionEnd = s +1;
            return false;
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="pdate" />
<div></div>