![](/img/trans.png)
[英]Jquery: Keyup event is not fired, on dynamically added input controls
[英]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.