[英]How can I force numbers only on a dynamically created field?
I am trying to restrict a dynamic field to numbers only but if I try: 我试图将动态字段限制为仅数字,但是如果我尝试:
$(document).on('keydown', '.numberOnly', function() {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || (e.keyCode == 65 && (e.ctrlKey ===
true || e.metaKey === true)) || (e.keyCode >=
35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode >
57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
But it doesn't work. 但这是行不通的。 it does work if I replace the top line with:
如果我将顶行替换为:
$(".numberOnly").keydown(function(e) {
however, that only works for static fields. 但是,这仅适用于静态字段。
Your method looks just fine, and should work correctly. 您的方法看起来还不错,并且应该可以正常工作。 There was one small typo that you left out the EventObject
e
from the delegated event binder ( but included it in the direct event binder, which is why it worked ). 您从委托事件绑定器中遗漏了EventObject
e
(这是一个小错字)(但将其包含在直接事件绑定器中,这就是它起作用的原因)。
Changing the first line to: 将第一行更改为:
$(document).on('keydown', '.numberOnly', function(e) {
should fix your problem 应该解决你的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.