preventDefault() on keyup event not working

前端 未结 4 1034
不思量自难忘°
不思量自难忘° 2021-02-19 06:20

I cannot get preventDefault() to work.

Here are some different code variations I have tried:

First:

$(document).keyup(function (evt)         


        
相关标签:
4条回答
  • 2021-02-19 06:43

    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/

    0 讨论(0)
  • 2021-02-19 06:45

    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.

    0 讨论(0)
  • 2021-02-19 06:50

    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/

    0 讨论(0)
  • 2021-02-19 07:02

    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/

    0 讨论(0)
提交回复
热议问题