【问题标题】:Display a computed observable in a text input在文本输入中显示计算出的 observable
【发布时间】:2015-12-07 02:54:26
【问题描述】:

为什么我的示例代码中的文本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 编辑问题。

标签: knockout.js computed-observable


【解决方案1】:

你的代码很好。

Knockout 在值改变时调用write 方法——这通常发生在焦点离开文本框时。尝试更改值,然后按 Tab - 您应该会看到显示的值发生变化。

如果您想更新每次按键的显示,您可以尝试 [textInput 绑定][1],但不建议这样做,因为它往往会与键入过程发生冲突。试试

[1]: http://knockoutjs.com/documentation/textinput-binding.html "textInput binding",但是对于这样的字段,您可能会发现它不适合,因为它会随着您的键入而改变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 2021-04-10
    相关资源
    最近更新 更多