これがページの最初の表示です (実際には、行と列のデータはサーバー コードとデータベースから生成されます)。各データの属性にもご注意ください
<table>
<tr>
<td id="1" class="decorate">Item3</td>
<td class="decorate"><p>Description<p></td>
</tr>
<tr>
<td class="decorate">Item1</td>
<td class="decorate"><p>Description1</p><p>Description2</p></td>
</tr>
<tr>
<td id="2" class="decorate">Item2</td>
<td class="decorate"><p>Description3<p></td>
</tr>
</table>
<div id="tablediv"></div>
OnLoad イベントでそのデータを読み取り、並べ替え後にデータを「tablediv」に追加する js コードを次に示します。
$(document).ready(function() {
var arr = new Array();
$('table tr').each(function() {
var $row = $(this);
var key = $row.find('td:first').html();
var value = $row.find('td:last').html();
console.log(value);
arr.push([key, value]);
});
arr.sort(function(a, b) {
var valueA, valueB;
valueA = a[0]; // sort by the first value of array
valueB = b[0];
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
return 0;
});
var root=document.getElementById('tablediv');
var table=document.createElement('table');
var tbo=document.createElement('tbody');
var row, cell;
for(var i=0;i<arr.length;i++)
{
row=document.createElement('tr');
for(var j=0;j<2;j++)
{
cell=document.createElement('td');
cell.appendChild(document.createTextNode(arr[i][j]));
row.appendChild(cell);
}
tbo.appendChild(row);
}
table.appendChild(tbo);
root.appendChild(table);
});
ただし、前のテーブルを完全に置き換えるのは好きではありませんtablediv
(前のテーブルには、jquery コードのどこにあるかを伝えるための ID またはクラスがありません)。
これどうやってするの ?また、前のテーブルの td 内の属性も保持したいと思います。ここでの配列の使用には、さらに実装が必要です...:-(