如何使用knockout或jquery对数据绑定列进行求和?

时间:2016-02-24 12:16:03

标签: javascript jquery knockout.js

我认为我有以下表格:

 <table border="0" id="tbl">
    <tr class="te">
        <th>DATE</th>
        <th>METHOD</th>
        <th>DEPOSIT</th>
        <th>WITHDRAWAL</th>
        <th>MEMO</th>
    </tr>
    <!-- ko foreach: account -->
    <tr>
        <td><span data-bind="text: transactionDate"></span></td>
        <td><span data-bind="text: tranType"></span> </td>
        <td><span data-bind="text: deposit"></span></td>
        <td><span data-bind="text: withdrawal"></span> </td>
        <td></td>
    </tr>
    <!-- /ko -->
    <tr class="last">
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>***TOTAL DEPOSIT --- SHOULD GO HERE***</td>
        <td>***TOTAL WITHDRAWAL --- SHOULD GO HERE***</td>
        <td>""</td>
    </tr>
</table>

请参阅下面的帐户解锁对象:

var Account = function (data) {
    this.transactionDate = ko.observable(data.transactionDate);
    this.payorPayee = ko.observable(data.payorPayee);
    this.amount = ko.observable(data.amount);
    this.isDebit = ko.observable(data.isDebit);
    this.tranType = ko.observable(data.tranType);

    this.deposit = ko.pureComputed(function () {
        //some code
    });
    this.withdrawal = ko.pureComputed(function () {
        //some code
    });
}

如您所见,我遍历帐户对象并在表格上显示信息。

带有帐户信息的JSON如下所示:

[{
    "transactionDate": "1/1/2016",
    "payorPayee": "AAAAA",
    "amount": "111",
    "isDebit": false,
    "tranType": "qqqq"
}, {
    "transactionDate": "1/1/2016",
    "payorPayee": "BBBBB",
    "amount": "222",
    "isDebit": false,
    "tranType": "wwww"
}, {
    "transactionDate": "1/1/2016",
    "payorPayee": "CCCCC",
    "amount": "333",
    "isDebit": false,
    "tranType": "eeee" 
}]

我需要做的是遍历行,对存款字段求和并在总存款字段中显示总数(最后&#39; tr&#39;),然后重复提取字段的过程。 我怀疑它是否更有意义在页面加载或使用Knockout时使用Jquery。

任何想法都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

就像您在 unsigned char hash[CC_SHA256_DIGEST_LENGTH]; if ( CC_SHA256([data bytes], [data length], hash) ) { NSData *sha256 = [NSData dataWithBytes:hash length:CC_SHA256_DIGEST_LENGTH]; NSString *hash=[sha256 description]; hash = [hash stringByReplacingOccurrencesOfString:@" " withString:@""]; hash = [hash stringByReplacingOccurrencesOfString:@"<" withString:@""]; hash = [hash stringByReplacingOccurrencesOfString:@">" withString:@""]; return hash; } return nil; deposit计算中所做的那样,您还应该在viewmodel中为总存款和总提款计算一个计算的observable。您只需循环遍历withdrawal数组并提取存款和取款的总和。

例如:

account

依此类推,只需为this.totalDeposit = ko.computed(function(){ var sum = 0; //i don't know if account is observableArray or just plain array this.account.forEach(function(account){ sum += Number(account.deposit()); }); return sum; }); 创建另一个计算。