我在編寫此起來了個去:
下面是基本標記:
<table id="table" data-bind="template: { name: 'table-template' }">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody>
<tr>
<td>Richard</td>
<td>Willis</td>
</tr>
<tr>
<td>John</td>
<td>Smith</td>
</tr>
</tbody>
</table>
<!-- Here is the template we'll use for re-building the table -->
<script type="text/html" id="table-template">
<thead>
<tr>
<th>Name</th>
<th>Surname</th>
</tr>
</thead>
<tbody data-bind="foreach: data">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: surname"></td>
</tr>
</tbody>
</script>
的Javascript:http://knockoutjs.com/documentation/plugins-mapping.html
:
(function() {
function getTableData() {
// http://johndyer.name/html-table-to-json/
var table = document.getElementById('table');
var data = [];
var headers = [];
for (var i = 0; i < table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi, '');
}
// go through cells
for (var i = 1; i < table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j = 0; j < tableRow.cells.length; j++) {
rowData[headers[j]] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
var Vm = function() {
this.data = ko.observableArray(getTableData());
};
ko.applyBindings(new Vm(), document.getElementById('table'));
})();
您可以使用映射插件創建每一行觀測這個概念延伸
在這裏查看演示:http://jsfiddle.net/CShqK/1/
編輯:我不是說這是最好的方法,因爲遍歷一個大表來獲取數據可能代價高昂。我可能會在該頁面中的其他人所建議的頁面中輸出JSON。
您可以在JavaScript變量中設置的初始數據,然後添加到可觀察到的,而不是在服務器中使用的foreach。 – MuriloKunze
在做這件事時你面臨的問題是什麼?它是完全地可能, – paritosh
@MuriloKunze:他說的JavaScript可能會被禁用。如果JavaScript被禁用,他不能使用JavaScript變量。 –