我正在寻找一种方法将此解决方案应用于所有具有<input type="number">
.
到目前为止,我只看到了使用 jQuery 按 ID 查找元素然后附加输入过滤器的方法。但是,我想要实现的是将这样的过滤器添加到具有“数字”类型的所有元素中。
例子:
<html>
<body>
<div>
<input type="number">
</div>
</body>
</html>
JS功能:
// Restricts input for the set of matched elements to the given inputFilter function.
(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));
将修饰符应用于特定元素
$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
return /^\d*$/.test(value); // Allow digits only, using a RegExp
});
});
更新: 我尝试了以下方法:
(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));
if($('input[type="number"]').length > 0){
$('input[type="number"]').each(function(index, element){ console.log(element); // Successfully logs the element!
element.inputFilter(function(value) { // I need to find ALL elements with input type = number here instead of just myTextBox
return /^\d*$/.test(value); // Allow digits only, using a RegExp
});
})
}