从 $(document).ready 获取按键功能创建的文本输入



我的JavaScript/JQuery中有一个函数,可以在$(document(.ready上填充一个表单。

$(document).ready(function build_item_table() {
    for (var x = 1; x <= 20; x++) {
        $('#item_table tbody').append("<tr>");
        $('#item_table tbody').append("<td><select id="item_" + x + "_budget" name="item_" + x + "_budget" class="item_budget" width="110px"><option>Loading...</option></select></td>");
        $('#item_table tbody').append("<td><input type="text" id="item_" + x + "_code" name="item_" + x + "_code" class="code_textbox" size="20"></td>");
        $('#item_table tbody').append("<td><input type="text" id="item_" + x + "_description" name="item_" + x + "_description" class="desc_textbox" size="83"></td>");
        $('#item_table tbody').append("<td><input type="text" id="item_" + x + "_quantity" name="item_" + x + "_quantity" class="cost_textbox" size="7" value="0" required></td>");
        $('#item_table tbody').append("<td>$&nbsp;<input type="text" id="item_" + x + "_unit" name="item_ " + x + "_unit" class="qty_textbox" size="10" value="0.00" required></td>");
        $('#item_table tbody').append("<td>$&nbsp;<input type="text" id="item_" + x + "_total" name="item_" + x + "_total" class="cost_textbox" size="10" value="0.00" required></td>");
        $('#item_table tbody').append("</tr>");
    }
});

但是,我想通过这个函数验证一些文本输入(顺便说一句,我对这个函数没有任何荣誉,因为我从这个伟大的社区找到了它(:

$('.cost_textbox').keypress(function(eve) {
  if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0) ) {
    eve.preventDefault();
  }
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.cost_textbox').keyup(function(eve) {
  if($(this).val().indexOf('.') == 0) {    
    $(this).val($(this).val().substring(1));
  }
 });
});

这适用于 HTML 代码中生成的输入文本框,但不适用于 JavaScript 中附加的输入文本框。我该如何解决这个问题?提前谢谢。

您需要

使用 .on('xxx') 函数而不是 .xxx() 进行委派:动态创建的元素不会触发基本事件。您需要将侦听器放在不会更改的父级上。

$('body').on('keypress','.cost_textbox',function(eve) {
  if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0) ) {
    eve.preventDefault();
  }
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('body').on('keyup','.cost_textbox',function(eve) {
  if($(this).val().indexOf('.') == 0) {    
    $(this).val($(this).val().substring(1));
  }
 });
});

最新更新