function myViewModel() { var self = this; // 繫結陣列 self.dataCollection = ko.observableArray(); // 新增資料 self.addData = function () { self.dataCollection.push(parseInt((Math.random() * 100))); }; // 移除資料 self.removeData = function (data) { self.dataCollection.remove(data); }; } ko.applyBindings(new myViewModel());
<div> <input type="button" value="Add" data-bind="click:addData" /> <table> <tbody data-bind="foreach:dataCollection"> <tr> <td> Index:<span data-bind="text:$index"></span> </td> <td> Data:<span data-bind="text:$data"></span> </td> <td><input type="button" value="remove" data-bind="click:$root.removeData" /></td> </tr> </tbody> </table> </div>