keyup,keydown和keypress事件无法在移动设备上运行

时间:2017-11-24 18:27:50

标签: javascript jquery

我一直试图让这个工作起来,但我不知道发生了什么,我的代码:

$('#buscar-producto').on('keydown', function(e){
    console.log('hello');
    console.log(e.keyCode);
});

它适用于计算机,但不适用于移动设备..

修改 我需要在按下某个键时获取keyCode ...

1 个答案:

答案 0 :(得分:2)

keydown 工作,但您可以使用似乎对Android手机产生不良影响的input事件...
要获取按下的键的代码,请使用jQuery的规范化Event.which

Android Chrome 已经过测试:

使用input事件(e.which始终提供0所以它似乎是Android设备上的错误)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('input', function(e){
    var key = e.which || this.value.substr(-1).charCodeAt(0);
    alert( key )
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

使用keydown(按预期工作)

jQuery(function($) { // DOM ready and $ alias secured

  $('#buscar-producto').on('keydown', function(e){
    alert( e.which );
  });

});
<input type="text" id="buscar-producto" placeholder="Buscar...">

<script src="https://code.jquery.com/jquery-3.1.0.js"></script>

相关问题