我想要一个带有2种状态的html数字文本框,当聚焦时,它必须显示所有小数位,而当聚焦丢失时,仅显示2个小数.我几乎实现了.
HTML:
<input data-bind="attr: { 'data-numericvalue': valueToRound}" class="numerictextbox" type="number"/>
Javascript:
var viewModel = { valueToRound: ko.observable(7.4267),};//NUMERIC TEXTBOX BEHAVIOUR$('.numerictextbox').focusout(function () { $(this).attr("data-numericvalue", this.value); //this line does not update the viewModel this.value = parseFloat($(this).attr("data-numericvalue")).toFixed(2);});$('.numerictextbox').focusin(function () { if ($(this).attr("data-numericvalue") !== undefined) this.value = $(this).attr("data-numericvalue");});ko.applyBindings(viewModel);
Jsfiddle:https://jsfiddle.net/7zzt3Lbf/64/
但是我的问题是,发生聚焦时,它不会更新绑定属性(在这种情况下为viewModel).这是我的代码的简化版本,因此我希望它对我的实际场景中的许多属性通用.
解决方法:
您混入了太多的jQuery 🙂
淘汰赛具有事件绑定和hasFocus绑定以处理UI输入.
在下面的示例中,我创建了一个视图模型,该模型具有可观察到的隐藏realValue,该值存储未修改的输入.当showDigits为false时,displayValue将此数字限制为2位数字.
我使用过hasFocus来跟踪我们是否要显示整数:它链接到showDigits.
var ViewModel = function() { this.showDigits = ko.observable(true); var realValue = ko.observable(6.32324261); this.displayValue = ko.computed({ read: function() { return this.showDigits() ? realValue() : parseFloat(realValue()).toFixed(2); }, write: realValue }, this);};ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><input data-bind="value: displayValue, hasFocus: showDigits" type="number"/>
编辑:在注释中,计算式的代码过多了:这是将计算式的逻辑包装在可重用的扩展器中的方法:
ko.extenders.digitInput = function(target, option) { var realValue = target, showRealValue = ko.observable(false), displayValue = ko.computed({ read: function() { return showRealValue() ? realValue() : parseFloat(realValue()).toFixed(2); }, write: realValue }, this); displayValue.showRealValue = showRealValue; return displayValue;};var ViewModel = function() { this.value1 = ko.observable(6.452345).extend({ digitInput: true }); this.value2 = ko.observable(4.145).extend({ digitInput: true });};ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script><input data-bind="value: value1, hasFocus: value1.showRealValue" type="number"/><input data-bind="value: value2, hasFocus: value2.showRealValue" type="number"/>
来源:https://www.icode9.com/content-1-522901.html
联系客服