我无法以编程方式将元素添加到包含在数据表中的可观察数组中。
表格的每一行都有一个我希望影响的不同数组。
HTML 如下所示:
<div class='liveExample'>
<h2>Cases</h2>
<div id='contactsList'>
<table class='contactsEditor'>
<tr>
<th>Case Number</th>
<th>Stage</th>
<th>Users</th>
<th>Ids</th>
</tr>
<tbody data-bind="foreach: appearances ">
<tr>
<td>
<input data-bind='value: caseNumber' />
</td>
<td><input data-bind='value: caseStage' /></td>
<td>
<ul data-bind="foreach: subjects">
<li style="list-style-type:none;"><label data-bind="text: Name"/></li>
</ul>
</td>
<td>
<table>
<tbody data-bind="foreach: ids">
<tr>
<td><input data-bind='value: $data' /></td>
<td><a href='#' data-bind='click: $root.removeId'>Delete</a></td>
</tr>
</tbody>
</table>
<a href='#' data-bind='click: $root.addId'>Add number</a>
</td>
</tr>
</tbody>
</table>
</div>
<p>
<button data-bind='click: save, enable:appearances().length > 0'>Save to JSON</button>
</p>
<textarea data-bind='value: lastSavedJson' rows='5' cols='60' disabled='disabled'> </textarea>
</p>
数据和 JavaScript 如下所示:
enter code here
var initialData = [{
"Number": "12000009",
"Stage": "Inital",
"Subjects": [{
"Name": "Andrew McAdam"},
{
"Name": "Patrick Brown"}],
"Ids": [1]},
{
"Number": "12000010",
"Stage": "Inital",
"Subjects": [{
"Name": "John Smith"}],
"Ids": [2, 3]},
{
"Number": "12000011",
"Stage": "Inital",
"Subjects": [{
"Name": "James Bonner"}],
"Ids": [4]},
{
"Number": "12000012",
"Stage": "Processed",
"Subjects": [{
"Name": "Henrik Dalgleish"}],
"Ids": [5]}]
var AppearancesModel = function(appearances) {
var self = this;
self.appearances = ko.observableArray(ko.utils.arrayMap(appearances, function(appearance) {
return {
caseNumber: appearance.Number,
caseStage: appearance.Stage,
subjects: ko.observableArray(appearance.Subjects),
ids: ko.observableArray(appearance.Ids)
};
}));
self.addId = function(appearance) {
appearance.ids.push("");
};
self.removeId = function(id) {
$.each(self.appearances(), function() {
this.ids.remove(id)
})
};
self.save = function() {
self.lastSavedJson(JSON.stringify(ko.toJS(self.appearances), null, 2));
};
self.lastSavedJson = ko.observable("")
}
ko.applyBindings(new AppearancesModel(initialData));
我遇到的问题是,在单击“添加”按钮并输入一个值后,数组中的值是空字符串(我在创建新数组元素时添加的值)。
我认为问题在于我在获得值之前将新项目添加到数组中,但我认为它将绑定到新输入,因此当我执行 Save 函数时,新值将被反映。
上面的 JsFiddle 在http://jsfiddle.net/amcgoldrick/3h9GZ/
谢谢
安迪