preventDefault() on keyup event not working

2020-07-03 03:50发布

I cannot get preventDefault() to work.

Here are some different code variations I have tried:

First:

$(document).keyup(function (evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 192) {
        alert('192');
        return false;
    }
});

Second:

$(document).keyup(function (evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 192) {
        alert('192');
        evt.preventDefault();
    }
});

Third:

$(document).keyup(function (evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode;
    if (charCode == 192) {
        alert('192');
        evt.preventDefault();
        return false;
    }
});

Only alert works.
Everything works on Opera,but not on Chrome and IE Also tried keydown and keypress. On keypress script doesn't work. $('#thetext').keydown(function(evt){}); neither works this.
Here is whole code: http://bbullett.tk/test/kakey.html

Key 192 = `

I'm trying to insert some text or symbol instead of `

4条回答
仙女界的扛把子
2楼-- · 2020-07-03 04:33

see working example here http://jsfiddle.net/WGSvm/

In all three examples you have used

$(document).keyup(function (evt) {  });

I would say use particular div id instead of $(document).keyup(function (evt) { });

like $("#DivIdName").keyup(function (evt) { }); and also use onkeypress strictly, because if you use onkeyup it has already executed its default task of printing or whatever it is.

查看更多
我只想做你的唯一
3楼-- · 2020-07-03 04:39

Listening to keyup event is too late for calling preventDefault, try listening to keypress or keydown instead.

$('input[type=text], textarea').on('keydown', function(event){
    if (event.which == 192) {
        console.log('192');
        event.preventDefault();
    }
});

Note that jQuery normalizes which property and it's cross-browser.

http://jsfiddle.net/763ys/

查看更多
老娘就宠你
4楼-- · 2020-07-03 04:51

You are using JQuery, which normalises the differences between browsers, so you only need to to check the evt.which property. See the JQuery documentation: http://api.jquery.com/keyup/

As others have said - keyup is too late to stop the processing of the key. Use keydown or keypress instead. http://api.jquery.com/category/events/keyboard-events/

查看更多
我只想做你的唯一
5楼-- · 2020-07-03 04:53

There is no default behaviour for .keyup(); it fires after the key press which triggers the default behaviour. Use .keydown() or.keypress()` instead.

source: http://api.jquery.com/category/events/keyboard-events/

查看更多
登录 后发表回答