[英]Get the previous value on a keyup event
我有一個應用程序,當用戶點擊退格鍵(鍵代碼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/
感謝您查看這個 :)
您可以將先前的值保存在keydown
輸入的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()); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <input type="text"> <span></span>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.