html - 如何使用 jQuery 在 HTML 输入框中只允许数字空间和分数(1 1/2)格式?
问题描述
我正在创建一个网页,其中有一个输入文本,我希望在其中只允许数字空间和分数,例如 (1 1/2, 2 1/4, 4 1/2...)
通常 1 1/2 我们称之为 ONE AND HALF。
如何使用 jQuery 做到这一点
这是我在JSFiddle中的代码,但它没有按预期工作。
<input id="intTextBox">
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this.value)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
// Install input filters.
$("#intTextBox").inputFilter(function(value) {
return /^(?:(?:\d+\s)*\d+\/\d+|\d+)$/.test(value);
});
解决方案
您的正则表达式应包含 2 个部分:只有数字和带有可选数字部分的分数:
function test(input) {
let pattern = /^(?:(?:\d+\s)*\d+\/\d+|\d+)$/;
console.log(input, pattern.test(input))
}
test('1');
test('43534');
test('12/234');
test('1/2');
test('23 1/2');
test('1 1/2');
test('1.2');
test('a/b');
推荐阅读
- javascript - 删除数组中的重复项(拼接)
- visual-studio - 在哪里可以找到版本控制分支命名指南?
- python - Python条件追加json项目
- python - 在 python 中找到更大的矩阵中的小矩阵,但不知道如何(附图)
- flutter - RangeError(长度):无效值:只有有效值是 0:1. 抛出错误 'ErrorDescription' 的实例
- c# - 接受任何参数的方法,循环遍历它以搜索 DateTime 变量,更改它们并在 C# 中返回一个新对象
- java - 使用 Jenkins Job Builder 将参数传递给 Jenkins 构建的问题
- javascript - Facebook Graph API:在 HTML 网页上显示来自控制台的 JSON 数据
- html - 为什么我转换后的 html 字符串只显示第一行?
- tensorflow - 将微调保存的模型导出到 TensorFlow Lite 错误