<script src="~/Scripts/jquery-1.8.2.js"></script> <script src="~/Scripts/knockout-2.2.0.js"></script> <h2>Participants</h2> Here are the participants: <div data-bind="template: { name: 'person-template', foreach: items }"> </div> <script type="text/html" id="person-template"> <h3 data-bind="text: firstName"></h3> <p>Credits: <span data-bind="text: lastName"></span></p> <input type="button" name="name" value="button" data-bind="click: $root.add" /> <input type="button" name="name" value="del" data-bind="click: $root.del" /> </script> <script type="text/javascript"> function MyViewModel() { var self = this; self.items = ko.observableArray(); self.add = function () { console.log("sdfsd"); }; self.del = function (data) { self.items.remove(data); console.log(data.firstName); } } $(function () { var vm = new MyViewModel(); $.ajax({ type: "get", url: "/home/makedata", success: function (datas) { $.each(datas, function (i) { vm.items().push(datas[i]); }); ko.applyBindings(vm); } }); }); </script>
我在
$(function () {}里面给vm的items属性把从后台拿过来的数据赋值过去了 但是是用each循环push的 有什么好办法直接赋值吗 还是得必须这么做 我是刚接触knockout 求教 只有5分 了 谢谢
自己解决了