繁体   English   中英

关于删除的最后一个keyup事件未触发jquery

[英]Last keyup event on delete not fired jquery

我对“ keyup”事件有一个奇怪的行为:当我在输入字段中填写某些内容时,然后我删除了该值,则无法识别上一个删除keyup事件。

示例代码:

$('#input').on('keyup',function(){
 if($(this).val().length > 0){
    $('#text').html($(this).val())
 }
});

小提琴这里

任何解决方案或为什么这种奇怪的行为?

只需将比较器更改为>=而不是>

$('#input').on('keyup',function(){
    if($(this).val().length >= 0){
        $('#text').html($(this).val())
    }
});

在这里摆弄

更新

根据小提琴中描述的新问题,该解决方案可以基于jQuery数据

 $(function () { $('#input-deposit').on('keyup', function (e) { if ($(this).val().length >= 0) { $('#text').html($(this).val()) } }); // set the default of previousValue $('#input-deposit').data('previousValue', 0); $('#input-deposit').on('keyup', function (e) { var t = 2000; if (!isNaN(this.value) && this.value.length != 0) { // get the previous value var previousValue = parseFloat($('#input-deposit').data('previousValue')); var total = parseFloat($('#input-balance').val()); var deposit = parseFloat($(this).val()); $('#input-deposit').data('previousValue', deposit); // use previousValue t = total + previousValue - deposit; } else { // reset previousValue $('#input-deposit').data('previousValue', 0); } $('#input-balance').val(t.toFixed(2)); }); }); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <label>Deposit</label> <input type="text" value="" id="input-deposit"/> <label>Balance</label> <input type="text" value="2000" id="input-balance"/> <div id="text"></div> 

问题是:

if($(this).val().length > 0){

必须是:

if($(this).val().length >= 0){

片段:

 $(function () { $('#input').on('keyup',function(){ if($(this).val().length >= 0){ $('#text').html($(this).val()) } }); }); 
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <input type="text" value="" id="input"/> <div id="text"></div> 

暂无
暂无

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

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