JavaScript keypress event not raised on Android browser

六眼飞鱼酱① 提交于 2019-12-27 12:05:20

问题


I have created a simple code to handle keypress event:

var counter = 0;        
$('input').on('keypress', function () {
    $('div').text('key pressed ' + ++counter);
});

JSFiddle.

But keypress event handler is not raised on mobile browser (Android 4+, WindowsPhone 7.5+). What could be the issue?


回答1:


Try keyup will help you

var counter = 0;        
$('input').on('keyup', function () {
    $('div').text('key up ' + ++counter);
});



回答2:


I believe keypress is deprecated now. You can check in the Dom Level 3 Spec. Using keydown or keyup should work. The spec also recommends that you should use beforeinput instead of keypress but I'm not sure what the support of this is.




回答3:


$(document).ready(function() {
  var pattForZip = /[0-9]/;
  $('#id').on('keypress input', function(event) {
    if(event.type == "keypress") {
      if(pattForZip.test(event.key)) {
        return true;
      }
      return false;
    }
    if(event.type == 'input') {
      var bufferValue = $(this).val().replace(/\D/g,'');
      $(this).val(bufferValue);
    }
  })
})



回答4:


Yes, some android browser are not supporting keypress event, we need use to only keydown or keyup but will get different keycodes, to avoiding different key codes use the following function to get the keycode by sending char value.

Eg:

function getKeyCode(str) {
  return str && str.charCodeAt(0);    
}
function keyUp(){
 var keyCode = getKeyCode("1"); 
}



回答5:


Use jQuery's input event, like this:

$( 'input' ).on( 'input', function() {
    ...
} );

With this you can't use e.which for determining which key was pressed, but I found a nice workaround here: http://jsfiddle.net/zminic/8Lmay/




回答6:


I think it is bad idea to use other events in place of 'keypress'. What you need to do is just include a jQuery file into your project. A file named jQuery.mobile.js or quite similar (ex. jQuery.ui.js) of any version can help you.

You can download it from : https://jquerymobile.com/download/



来源:https://stackoverflow.com/questions/21055270/javascript-keypress-event-not-raised-on-android-browser

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!