我有一个 HTML 表格,想在上面定义一些 knockout.js 可观察对象。当我点击 createTrack 函数时,表格的现有内容再次被添加,想添加一个新条目来跟踪。需要帮助来解决此问题。
注意:我不想使用 JSON 动态获取内容,因为它会影响 SEO/其他原因。
链接到小提琴:http: //jsfiddle.net/ATDJp/1/
查看型号代码
(function () {
var tracks = ko.utils.parseHtmlFragment('#tracks-table');
// represent a single track item
var Track = function (TrackNo, TrackTitle, TrackLength) {
this.TrackNo = ko.observable(TrackNo);
this.TrackTitle = ko.observable(TrackTitle);
this.TrackLength = ko.observable(TrackLength);
};
var TracksViewModel = function (tracks) {
var self = this;
// All track
self.tracks = ko.observableArray(ko.utils.arrayMap(tracks, function (track) {
return new Track(track.TrackNo, track.TrackTitle, track.TrackLength);
}));
// Add a new Track on click of new button
self.createTrack = function () {
// Add a new Track
self.tracks.push({ TrackNo: "", TrackTitle: "", TrackLength: "" });
};
}
// check data from local table
// var tracks = ko.utils.parseJson(JSON.stringify(jQuery('#tracks-table').tableToJSON()));
// bind a new instance of our view model to the page
var TracksViewModel = new TracksViewModel(tracks || []);
ko.applyBindings(TracksViewModel);
})();