我试图修改此代码,但它无法正常工作……可能是一些小错误,但我无法调试它:(

// replace , with . and block writing letters
$(document).on("keydown", ".amount", function () {
      $(this).keydown(function(e) {
                if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
                    e.preventDefault();
                    $(this).val($(this).val() + '.');
                }
          var key = e.charCode || e.keyCode || 0;
          return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
      });
};


This is original code and it doesn't work on dynamic content
这就是为什么我要修改它!

最佳答案

当用户单击带有ForceNumericOnly的输入时,仅调用.amount方法怎么样?

$(document).on('focus', '.amount', function(){
    $(this).ForceNumericOnly();
});


https://jsfiddle.net/daveSalomon/r5n8xuhx/5/

您可以(应该)对其进行优化,以便在已经运行keydown代码的情况下不再添加ForceNumericOnly处理程序……

$.fn.ForceNumericOnly = function() {
    return this.each(function() {
        if($(this).data('forceNumberOnly'){ return; }
        $(this).data('forceNumberOnly',true);
        ...
    });
};


https://jsfiddle.net/daveSalomon/r5n8xuhx/6/

09-20 07:41