![](/img/trans.png)
[英]how to bind knockout's Observable array length to an html element
[英]Knockout Observable Array not binding future element in html
我創建了一個帶有可觀察的可剔除數組的簡單表,然后單擊按鈕,出現了另一個帶有選定項目的表。 但可觀察到的數組更改未綁定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>
我花了大約一天的時間來修復,但無法正常工作,請記住這是淘汰js的新手。 非常感謝您的回答。
您不能簡單地覆蓋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]);
}
}
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.