knockout 通过teplate实现简单的代码实现复杂的操作绑定checkbox,代码如下自我感觉很赞!!!
前台HTml
<ul data-bind="template: { name: 'choiceTmpl', foreach: choices, templateOptions: { selections: selectedChoices } }">
</ul><script id="choiceTmpl" type="text/html"> < li > <input type = "checkbox"data - bind = "attr: { value: $data }, checked: $item.selections" / ><span data - bind = "text: $data" > </span> </li > </script><hr /><div data-bind="text: ko.toJSON(selectedChoices)"></div><hr /><div data-bind="text: selectedChoicesDelimited"></div>前台JS
var viewModel = { choices: ["one", "two", "three", "four", "five"], selectedChoices: ko.observableArray(["two", "four"]) };
viewModel.selectedChoicesDelimited = ko.dependentObservable(function() { return this.selectedChoices().join(","); }, viewModel);
ko.applyBindings(viewModel);
在线Fiddle演示如下