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更简洁一些。 –
不客气托德!我很高兴这对你有一些帮助。问候 –