Javascript 敲除可观察数组不绑定html中的future元素
我已经用knockout observable数组创建了一个简单的表,点击按钮就会看到另一个表,其中包含选定的项。 但可观察的数组更改不绑定html视图。 这是我的密码Javascript 敲除可观察数组不绑定html中的future元素,javascript,html,arrays,knockout.js,Javascript,Html,Arrays,Knockout.js,我已经用knockout observable数组创建了一个简单的表,点击按钮就会看到另一个表,其中包含选定的项。 但可观察的数组更改不绑定html视图。 这是我的密码 <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <scr
<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>
$(函数(){
ViewModel=函数(){
var self=这个;
自身植物=[
{名称:“工厂1”,选定:真},{名称:“工厂2”,选定:假},{名称:“工厂3”,选定:真},{名称:“工厂4”,选定:假}
];
self.PlantSelected=ko.observearray([]);
self.gridSelectedSave=函数(obj){
控制台日志(obj);
this.temp=[];
self.PlantSelected=ko.observearray([]);
如果(对象长度>0){
对于(var i=0;i,可以在可观测数组中使用push方法
self.PlantSelected.push(obj[i]);
小提琴:
您不能简单地覆盖PlantSelected
变量,您需要保留原始引用。因此,您需要self.PlantSelected=ko.observatarray([]);
而不是self.PlantSelected.removeAll()
然后直接将“selected”项推入其中:self.PlantSelected.push(obj[i]);
self.gridSelectedSave=函数(obj){
self.PlantSelected.removeAll()
如果(对象长度>0){
对于(var i=0;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]);
}
}
}
};