在 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>
我也介绍了一个相同代码的博客,你可以点击这个链接查看