0
我有一個來自服務器的ajax數據和這個數據我應該生成選擇框。 請看this code:淘汰賽 - 如何使用選項和foreach綁定在一起
var dataCameFromServer = {
foo: "1",
bar: "sag",
results: [
{
slectedBoxID: null,
selectBoxOptions: [
{
id: 1,
name: "mosi"
},
{
id: 2,
name: "azi"
},
{
id: 3,
name: "mom"
},
{
id: 4,
name: "dad"
}
]
},
{
slectedBoxID: 2,
selectBoxOptions: [
{
id: 1,
name: "tehran"
},
{
id: 2,
name: "masal"
},
{
id: 3,
name: "gilan"
},
{
id: 4,
name: "rasht"
}
]
},
{
slectedBoxID: 1,
selectBoxOptions: [
{
id: 1,
name: "adidas"
},
{
id: 2,
name: "nike"
},
{
id: 3,
name: "rebook"
},
{
id: 4,
name: "puma"
}
]
}
]
};
function selectViewModel() {
var self = this;
this.data = ko.observable(dataCameFromServer);
this.sbValue = ko.observableArray();
ko.computed(function() {
$.each(self.data().results, function(i,v) {
self.sbValue.push(v.slectedBoxID);
});
});
ko.computed(function(){
console.log(self.sbValue());
});
}
ko.applyBindings(new selectViewModel(), $("#wrapper")[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="wrapepr">
<!-- ko with: data -->
<!-- ko foreach : results -->
<select data-bind="options:selectBoxOptions,optionsText: 'name',optionsValue: 'id',value: $root.sbValue()[$index],optionsCaption: 'Choose...'"></select>
<!-- /ko -->
<!-- /ko -->
</div>
我默認的是在slectedBoxID
如果我的選擇框,然後改變了相應slectedBoxID
變化值的選項中選擇想要我的選擇框。
有沒有什麼建議可以做到這一點?
p.s:我不知道服務器有多少結果,它不只是這三個結果!