我在看make an input only-numeric type on knockout。 接受的答案工作正常,但如何防止输入多个小数点(如4.4.4)(或如何防止第二个小数点?)
代码是这样的:
<input id="text" type="text" data-bind="numeric, value: number">
ko.bindingHandlers.numeric = {
init: function (element, valueAccessor) {
$(element).on("keydown", function (event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: . ,
(event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
}
};
答案 0 :(得分:0)
自定义绑定对我来说不太好看。我建议只使用Knockout Validation,这在我的工作流程中被证明是一个很棒的插件。语法很简单:ko.observable(...).extend({ number: true })
。您还可以添加最小/最大验证:.extend({ number: true, min: 0, max: 100 }) // percentage
,插件允许将css类添加到无效元素。
见下面的例子。它完全符合您的要求。
function viewModel() {
this.number = ko.observable(0).extend({ number: true });
}
ko.applyBindings(new viewModel(), document.body);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.js"></script>
<input data-bind="textinput: number" />
&#13;