我尝试修改此代码,但它不起作用...可能是一些小错误,但我无法调试它:(
// 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 这就是我想修改它的原因!
最佳答案
当用户点击带有 .amount
的输入时,仅调用 ForceNumericOnly
方法怎么样?
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});
https://jsfiddle.net/daveSalomon/r5n8xuhx/5/
您可以(应该)优化它,这样如果它已经运行了 ForceNumericOnly
代码,它就不会再次添加 keydown
处理程序...类似于:
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumberOnly'){ return; }
$(this).data('forceNumberOnly',true);
...
});
};
关于javascript - jQuery 防止写字母并将逗号更改为点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36859759/