我对 Knockout 相当(非常!)陌生,希望您能就以下问题为我指明正确的方向。
我在 jsFiddle 上找到了最终结果的示例
最终,我希望在表格行中有多个复选框,这些复选框绑定(bind)到价格(将动态加载)。该行的最后一个单元格将保存所有已选择价格的平均值(已选中复选框)。
这是我对 ViewModel 的了解:
//--Page ViewModel
//--Set the structure for the basic price object
function Price(quote) {
this.quote = ko.observable(quote);
}
//--Sets the structure for the contract month object
//--This includes the month, and array of Price and an average
function ContractMonthPrices(month, prices) {
this.month = month;
this.prices = $.map(prices, function(quote) { return new Price(quote); });
this.average = ko.computed(function() {
var total = 0;
for(var i = 0; i < this.prices.length; i++)
total += this.prices[i].quote();
return total;
}, this);
}
我知道这可能没用,但我们将不胜感激任何帮助!
谢谢!
最佳答案
假设您的源数据看起来像这样,我稍微修改了您的 fiddle :
var allPrices = [
{ month: 'January', prices: [ 3, 4, 4, 4 ] },
{ month: 'February', prices: [ 7, 8, 2, 3 ] },
{ month: 'March', prices: [ 7, 8, 2, 1 ] }
];
我已经用完整的数据绑定(bind)完全重写了您的标记。
为了获得average
computed observable 工作,我在你的每个价格中添加了selected
属性:
function Price(quote) {
this.quote = ko.observable(quote);
this.selected = ko.observable(true); // bound to checkbox in markup
}
您的代码也进行了大量更改和修复。
附言我已经将 $.map
更改为 ko.utils.map
因为 KO 有自己的方法来执行常见的数组操作。如果需要,您可以安全地继续使用 jQuery 方法。
关于javascript - 使用复选框构建表并使用 Knockout.js 绑定(bind)到数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16591166/