【发布时间】:2020-04-30 14:23:32
【问题描述】:
我正在寻找一种将this 解决方案应用于所有具有<input type="number"> 的字段的方法。
到目前为止,我只看到了使用 jQuery 按 ID 查找元素然后附加输入过滤器的方法。 但是,我想要实现的是将此类过滤器添加到具有“数字”类型的 all 元素中。
示例:
<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
});
})
}
【问题讨论】:
标签: javascript html jquery findelement