我想要一個(gè)帶有2種狀態(tài)的html數(shù)字文本框,當(dāng)聚焦時(shí),它必須顯示所有小數(shù)位,而當(dāng)聚焦丟失時(shí),僅顯示2個(gè)小數(shù).我?guī)缀鯇?shí)現(xiàn)了.
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:///7zzt3Lbf/64/
但是我的問題是,發(fā)生聚焦時(shí),它不會(huì)更新綁定屬性(在這種情況下為viewModel).這是我的代碼的簡(jiǎn)化版本,因此我希望它對(duì)我的實(shí)際場(chǎng)景中的許多屬性通用. 解決方法: 您混入了太多的jQuery ??
淘汰賽具有事件綁定和hasFocus綁定以處理UI輸入.
在下面的示例中,我創(chuàng)建了一個(gè)視圖模型,該模型具有可觀察到的隱藏realValue,該值存儲(chǔ)未修改的輸入.當(dāng)showDigits為false時(shí),displayValue將此數(shù)字限制為2位數(shù)字.
我使用過hasFocus來跟蹤我們是否要顯示整數(shù):它鏈接到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./ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: displayValue, hasFocus: showDigits" type="number"/>
編輯:在注釋中,計(jì)算式的代碼過多了:這是將計(jì)算式的邏輯包裝在可重用的擴(kuò)展器中的方法:
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./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./content-1-522901.html
|