【发布时间】:2016-10-10 00:23:31
【问题描述】:
我的目标是拥有一个动态增长的输入字段列表 - 每当我开始在输入字段中输入时,其下方应该会出现一个新的空字段。
我希望这样的事情能够奏效;
function Model() {
// Build a basic observable array
this.inputs = ko.observableArray();
// Whenever this changes, or on initial creation of this computed
// add a new empty field if the last one has any text in it.
ko.computed(function () {
var len = this.inputs().length;
// If there are no fields (initial run) or the last element is falsey...
if (!len || this.inputs()[len-1]()) {
// Create a new observable and add it to the array.
this.inputs.push(ko.observable(""));
}
}, this);
}
下面是一些用于绑定模型的基本 HTML;
<ul data-bind="foreach: inputs">
<li><input data-bind="textInput: $data" /></li>
</ul>
当我在正确显示的文本框中键入内容时(显示此函数在创建时运行),计算不会被调用。
那么我必须怎么做才能让计算结果正确地重新评估?有没有更好的方法来实现在淘汰赛中实际有效的动态增长列表?
这是jsfiddle 的确切代码,用于帮助调试此问题。
【问题讨论】:
标签: javascript html knockout.js