我有一个从列表中创建的表。我有一个添加到该列表的按钮。这真的很简单,但似乎无法找出我所缺少的。这是我的代码:
<table>
<thead>
<th>Value</th>
<th>Remove</th>
</thead>
<tbody data-bind="foreach: names">
<tr>
<td>
<span data-bind="text: $data"></span>
</td>
<td>
<img id="Remove" width="20px" height="20px" src="/Content/Images/delete.png" data-bind="click: $parent.removeValue">
</td>
</tr>
</tbody>
</table>
<div>
<h2>
<span data-bind="text: addValueError"></span>
</h2>
<label for="addValue">Add Value</label>
<input id="addValue" type="text" data-bind="value: newValue" />
<img id="add" width="20px" height="20px" src="/Content/Images/add.png" data-bind="click: addNewValue">
</div>
<script type="text/javascript">
var model= new Model($('#someDiv')[0], data);
</script>
JavaScript:
function Model($id, data) {
var self = this;
self.names = ko.observablearray(['1','2','3']);
self.removeValue = function(){
//remove
}
self.addValueError = ko.observable();
self.newValue = ko.observable();
self.addNewValue = function(){
if (self.newValue () != null && self.newValue ().length > 0) {
self.Names().push(self.newValue ());
self.newValue ('');
self.addValueError ('');
} else {
self.addValueError ('Please provide a value to add.');
}
};
ko.applyBindings(self, $id);
}
当我添加一个值时,它会添加到名称列表中,但不会在表中更新。有任何想法吗?