简体   繁体   English

如何在Javascript或Jquery中将侦听器设置为“ backspace press”事件?

[英]How to set listeners to “backspace press” event in Javascript or Jquery?

I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below: 我有一个启用或禁用的按钮,分别在输入中是否包含文本,如下面的代码片段所示:

var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');

$(input).on('keyup', function(){
  if((input.value != null) && (input.value != ''))
    $(btn).removeClass('btnDisabled');
  else
    $(btn).addClass('btnDisabled');
});

Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. 使用keyup事件,在我使用Android 6.0.1的smarthphone上的应用中效果很好。 But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled. 但是由于某种原因,在装有Android 4.4.2的平板电脑上,如果按下Backspace键直到输入开始,并且擦除了所有文本值,则该按钮仍处于启用状态。 I researched this problem but I'm still not sure if the WebView version interferes with this. 我研究了此问题,但仍不确定WebView版本是否会对此造成干扰。 I think so. 我认同。

I used other code snippets to see if the event is triggered by the "backspace" button, as shown below: 我使用其他代码片段来查看事件是否由“退格”按钮触发,如下所示:

  $(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
      var key = event.keyCode || event.charCode;

      console.log("keydown " + key, "length " + input.value.length);
      //if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
    });

With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0. 通过此测试,我看到退格键不会触发事件,并且变量key始终等于0。

I need to disable the button when input is empty. 输入为空时,我需要禁用该按钮。 Where am I going wrong? 我要去哪里错了?

Right now, I thank those who help! 现在,我感谢那些帮助! :D :d

There is another event that you can use: input 您可以使用另一个事件: input

https://developer.mozilla.org/en-US/docs/Web/Events/input https://developer.mozilla.org/en-US/docs/Web/Events/input

The DOM input event is fired synchronously when the value of an <input> , <select> , or <textarea> element is changed. 更改<input><select><textarea>元素的值时,将同步触发DOM输入事件。

In this case, change 在这种情况下,请更改

$(input).on('keydown', 

to

$(input).on('input', 

See also: https://caniuse.com/#search=input 另请参阅: https : //caniuse.com/#search=input

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM