为什么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>