我创建了一个带有knockout observable数组的简单表,然后在按钮上单击另一个包含所选项的表。 但是可观察的数组更改没有绑定html视图。 这是我的小提琴代码
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
<script type="text/javascript">
$(function(){
ViewModel = function(){
var self = this;
self.plant = [
{name:"plant 1",selected:true},{name:"palnt 2",selected:false},{name:"plant 3",selected:true},{name:"plant 4",selected:false}
];
self.PlantSelected = ko.observableArray([]);
self.gridSelectedSave = function(obj){
console.log(obj);
this.temp = [];
self.PlantSelected = ko.observableArray([]);
if(obj.length > 0){
for(var i = 0;i<obj.length;i++){
if(obj[i].selected){
this.temp.push(obj[i]);
}
}
}
self.PlantSelected = ko.observableArray(this.temp);
console.log(self.PlantSelected());
};
};
ko.applyBindings(new ViewModel());
});
</script>
</head>
<body>
<table>
<tbody data-bind="foreach: plant">
<tr>
<td>
<span data-bind="text: name"></span>
</td>
</tr>
</tbody>
</table>
<hr/>
<table>
<tbody data-bind="foreach: PlantSelected">
<tr>
<td>
<span data-bind="text: name"></span>
</td>
</tr>
</tbody>
</table>
<br/><hr/>
<div data-bind="click: function(){
$root.gridSelectedSave(plant);
}">click to show selected</div>
</body>
我花了大约一天时间修复但没有工作,请记住,这是淘汰赛的新手。非常感谢你的回答。
答案 0 :(得分:3)
您不能简单地覆盖PlantSelected
变量,您需要保留原始参考。因此,您需要self.PlantSelected = ko.observableArray([]);
而不是self.PlantSelected.removeAll()
,而是将“已选定”项直接推入其中:self.PlantSelected.push(obj[i]);
。
self.gridSelectedSave = function(obj){
self.PlantSelected.removeAll()
if(obj.length > 0){
for(var i = 0;i<obj.length;i++){
if(obj[i].selected){
self.PlantSelected.push(obj[i]);
}
}
}
};
答案 1 :(得分:0)