获取keyup事件的先前值

时间:2018-02-08 11:06:42

标签: javascript jquery html

我有一个应用程序,当用户点击退格键(键代码8)并且值为空时,我想要做某事。但是当我用keyup事件尝试时,我会在按下按键后得到值,这不是我想要的。 另外我不想使用keydown,因为我想获得其他东西的当前值。

基本上,GOTCHA会在没有值并且按下退格键时触发,但是当有一个刚删除的角色时它会触发。

我想要的是,只有当输入的前一个值为空时才记录GOTCHA。

$(document).ready(() => {
  $('input').on('keyup', e => {
    // this is the condition for now, it need to be edited
    const condition = !$(e.target).val().length && e.keyCode === 8;
    if (condition) {
      console.log('GOTCHA'); // this fires before it should be fired
    }
    console.log($(e.target).val().length + ', ' + e.keyCode);
  });
  $('input').on('keydown', e => {
    console.log($(e.target).val().length + ', ' + e.keyCode);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text">
<span></span>

这是一个小提琴,让您了解我想要实现的目标 https://jsfiddle.net/0z4cyj2e/1/

感谢您对此进行调查:)

1 个答案:

答案 0 :(得分:2)

您可以在[{1}}输入的data道具中保存之前的值。

keydown
$(document).ready(() => {
  $('input').on('keyup', e => {
    // this is the condition for now, it need to be edited
    const condition = !$(e.target).data('previousValue').length && e.keyCode === 8;
    if (condition) {
      console.log('GOTCHA'); // this fires before it should be fired
    }
    console.log($(e.target).val().length + ', ' + e.keyCode);
  });
  $('input').on('keydown', e => {
    console.log($(e.target).val().length + ', ' + e.keyCode);
    $(e.target).data('previousValue', $(e.target).val());
  });
});