Here at Jsfiddle你會發現你的問題的工作解決方案,它也會顯示選定的位置。
的HTML代碼爲:
<div data-bind="template: { name: 'locationTmpl', foreach: locations, templateOptions: { selections: selectedLocations } }">/</div>
<script id="locationTmpl" type="text/html">
<input type="checkbox" data-bind="attr: { value: $data }, checked: $data.isSelected" />
<span data-bind="text: $data.DisplayName"></span>
</script>
<hr />
<div data-bind="text: JSON.stringify(ko.toJS(selectedLocations), null, 2)"></div>
<hr />
JavaScript代碼是:
<script type="text/javascript">
function MyLocation(locationId, displayName, selected) {
this.LocationId = ko.observable(locationId);
this.DisplayName = ko.observable(displayName);
this.isSelected = ko.observable(selected);
}
var viewModel = function (items) {
this.locations = ko.observableArray([
new MyLocation('1', 'Starbucks1'),
new MyLocation('2', 'Starbucks2', true),
new MyLocation('3', 'Starbucks3'),
new MyLocation('4', 'Starbucks4'),
new MyLocation('5', 'Starbucks5')
]);
//self.selectedLocations = ko.observableArray([self.locations()[1]]);
this.selectedLocations = ko.computed(function() {
return ko.utils.arrayFilter(
this.locations(), function (item) {
return item.isSelected();
}
);
}, this);
};
ko.applyBindings(new viewModel());
</script>
我已經介紹的相同的代碼,博客,以及,你可以檢查它by clicking this link
謝謝伊姆蘭。您的意見非常有幫助,我讚賞selectedLocations的額外細分。另一個答案得到了信譽,因爲它是第一個,兩個答案几乎相同,並且SethCran的selectedLocation更簡潔一些。 –
不客氣託德!我很高興這對你有一些幫助。問候 –