我正在尝试创建一个包含内部数组的新帐户,但是我收到错误:
为什么这不起作用?
<script>
function Account(id, name, balance, deposits) {
this.Id = id;
this.Name = name;
this.Balance = balance;
this.Deposits = deposits;
}
var myAccountViewModel = function ()
{
this.Accounts = ko.observableArray([
new Account(1, "A1", 100, [1,2]),
new Account(2, "A2", 200, [2]),
new Account(3, "A3", 300, [2, 3]),
new Account(4, "A4", 400, [2,3]),
])
}
ko.applyBindings(myAccountViewModel);
</script>
HTML
<table>
<thead>
<tr>
<th>S.No</th>
<th>ID</th>
<th>Name</th>
<th>Balance</th>
</tr>
</thead>
<tbody data-bind="foreach: {data:Accounts, as:'Account'}">
<tr>
<td data-bind="text:($index()+1)"></td>
<td data-bind="text:Account.Id"></td>
<td data-bind="text:Account.Name"></td>
<td data-bind="text:Account.Balance"></td>
<!--<td>
<ul data-bind="foreach: {data:Deposits, as:'Amount'}">
<li data-bind="text:(Account().Name + 'Deposited ' + Amount())"></li>
</ul>
</td>-->
</tr>
</tbody>
</table>
答案 0 :(得分:1)
问题中的代码对我有用。以下是适用于@alwaysVBNET的版本。 - 它基本上是问题中代码的内容,稍作修改。我从http://knockoutjs.com/downloads/knockout-3.4.2.js
下载了KO 3.4.2主要的变化是在将temp
变量添加到可观察数组之前使用它来实例化Account
个对象。如果有人能解释为什么这会产生影响,我会很感兴趣。
<!doctype html>
<html>
<head>
<title>KO js test</title>
<script src=./knockout-3.4.2.js></script>
</head>
<body>
<table>
<thead>
<tr>
<th>S.No</th>
<th>ID</th>
<th>Name</th>
<th>Balance</th>
</tr>
</thead>
<tbody data-bind="foreach: {data:Accounts, as:'Account'}">
<tr>
<td data-bind="text:($index()+1)"></td>
<td data-bind="text:Account.Id"></td>
<td data-bind="text:Account.Name"></td>
<td data-bind="text:Account.Balance"></td>
<td>
<ul data-bind="foreach: {data:Deposits, as:'Amount'}">
<li data-bind="text:(Account.Name + 'Deposited ' + Amount)"></li>
</ul>
</td>
</tr>
</tbody>
</table>
<script>
"use strict";
function Account(id, name, balance, deposits) {
var self = this;
self.Id = id;
self.Name = name;
self.Balance = balance;
self.Deposits = deposits;
}
var MyAccountViewModel = function ()
{
var self = this;
self.Accounts = ko.observableArray();
var temp = new Account(1, "A1", 100, [1,2]);
self.Accounts.push(temp);
temp = new Account(2, "A2", 200, [2]);
self.Accounts.push(temp);
temp = new Account(3, "A3", 300, [2, 3]);
self.Accounts.push(temp);
temp = new Account(4, "A4", 400, [2,3]);
self.Accounts.push(temp);
}
ko.applyBindings(new MyAccountViewModel());
</script>
</body>
</html>