1
爲什麼我的示例代碼中的文本input
只顯示輸入到其中的數值,而不是帶有「$
」的格式值?在文本輸入中顯示計算的可觀察值
function MyViewModel() {
var self = this;
this.price = ko.observable(25.99);
this.formattedPrice = ko.computed({
read: function() {
return "$" + self.price().toFixed(2);
},
write: function (value) {
// Strip out unwanted characters, parse as float, then write the raw data back to the underlying "price" observable
value = parseFloat(value.replace(/[^\.\d]/g, ""));
self.price(isNaN(value) ? 0 : value); // Write to underlying storage
},
owner: self
});
}
ko.applyBindings(new MyViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>Price: <input data-bind="value: formattedPrice" /></p>
當我運行你的代碼時,它工作得很好。與sinppet編輯問題。 – Dnyanesh