gpt4 book ai didi

javascript - 如何动态添加列和行来计算 knockout 中每个单元格的总数

转载 作者:行者123 更新时间:2023-11-28 12:33:30 25 4
gpt4 key购买 nike

我有一个像这样的简单示例数据

var data = {
"Lines": [
{"Entries": [{"Hours": 5.5},{"Hours": 2.50},{"Hours": 3.75}]},
{"Entries": [{"Hours": 5.1},{"Hours": 2.00},{"Hours": 4.75}]},
{"Entries": [{"Hours": 1.2},{"Hours": 3.00},{"Hours": 2.12}]
}]
}

这是我的模型

function ViewModel() {
var self = this
self.List = ko.observableArray([])

self.LoadData = function () {
var data = {
"Lines": [
{"Entries": [{"Hours": 5.5},{"Hours": 2.50},{"Hours": 3.75}]},
{"Entries": [{"Hours": 5.1},{"Hours": 2.00},{"Hours": 4.75}]},
{"Entries": [{"Hours": 1.2},{"Hours": 3.00},{"Hours": 2.12}]
}]
}
self.List(ko.mappings.fromJS(data.Lines))
////this makes every child observable
}
self.LoadData()
}

$('document').ready(function () {
ko.applyBindings(new ViewModel())
})

这是我的观点

<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Mon 1 </th>
<th>Mon 2 </th>
<th>Mon 3 </th>
</tr>
</thead>
<tbody data-bind='foreach:Lines'>
<tr data-bind='foreach:$data.Entries'>
<td>
<input type="text" data-bind="value:Hours"/>
</td>
</tr>
</tbody>
</table>

这是示例 View

enter image description here

这是我想要的输出

enter image description here

您可以看到我正在添加需要添加的列和行,这些应该是可观察的。我该怎么做。我不知道从哪里开始。

最佳答案

您只需向每一行添加一个compatedObservable(更新的 fiddle :http://jsfiddle.net/kL79d/4/):

html:

<table id="myTable" class="tablesorter">
<thead>
<tr>
<th>Mon 1 </th>
<th>Mon 2 </th>
<th>Mon 3 </th>
<th>Total </th>
</tr>
</thead>
<tbody data-bind='foreach:List'>
<tr>
<!-- ko foreach:Entries-->
<td>
<input type="text" data-bind="value:Hours, valueUpdate:'afterkeydown'"/>
</td>
<!-- /ko -->
<td>
<span data-bind="text:Total"></span>
</td>
</tr>
</tbody>
</table>

js:

function ViewModel() {
var self = this
self.List = ko.observableArray([])

self.LoadData = function () {
var data = {
"Lines": [
{"Entries": [{"Hours": 5.5},{"Hours": 2.50},{"Hours": 3.75}]},
{"Entries": [{"Hours": 5.1},{"Hours": 2.00},{"Hours": 4.75}]},
{"Entries": [{"Hours": 1.2},{"Hours": 3.00},{"Hours": 2.12}]
}]
}
self.List(ko.mapping.fromJS(data.Lines)())
////this makes every child observable
}

self.applyTotals = function(){
ko.utils.arrayForEach(self.List(), function(vm){
vm.Total = ko.computed(function(){
var s = 0;
ko.utils.arrayForEach(this.Entries(), function(entry){
var p = parseFloat(entry.Hours(), 10);
if (!isNaN(p)) {
s += p;
}
});
return s;
}, vm);
});
}

self.LoadData();
console.log(self.List());
self.applyTotals();
}

ko.applyBindings(new ViewModel())

要获取列总计,请在垂直方向上执行相同的操作。为了更轻松地访问数据值,您可能希望将数据保留在允许轻松迭代行和列的数据结构中。

关于javascript - 如何动态添加列和行来计算 knockout 中每个单元格的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19680580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com