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

Text Input Created from $(document).ready Get Keypress Function

我的 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));
  }
 });
});