在淘汰赛中仅输入数字类型 [英] make an input only-numeric type on knockout
本文介绍了在淘汰赛中仅输入数字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我阅读了很多教程,但我不知道该怎么做,这是输入
i read many tutorials but i dont know how to do this, this is the input
input(type="text",name="price",id="price"data-bind="text: price,valueUpdate:['afterkeydown','propertychange','input']")
这是我的viewModel
and this is my viewModel
price: ko.computed(function()
{
return parseFloat(this.replace(' ','').replace(/[^0-9\.]+/g,"")) || '';
},this)
但这会导致错误:这没有方法更换???如何将价格值传递给计算函数??
but this cause error: this has no method replace??? how can i pass the price value to the computed function??
推荐答案
最好创建自定义绑定 http://knockoutjs.com/documentation/custom-bindings.html ,只接受允许的字符[0-9, 。]作为数字表示。
Is better to create custom binding http://knockoutjs.com/documentation/custom-bindings.html which accept only allowed characters [0-9,.] as numeric representation.
将此行放入您的视图中
<input id="text" type="text" data-bind="numeric, value: number">
将此行放入模型中(记得将数字绑定为可观察属性)
put this line into your model (remember to bind number as observable property)
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();
}
}
});
}
};
这篇关于在淘汰赛中仅输入数字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文