DOCTYPE HTML html head meta charset utf-8 style table th td border 1px

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<!DOCTYPE HTML>
<html>
<head><meta charset="utf-8">
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
</head>
</html>
<body>
<button id="jsbutton" onclick="sortTable()">ChangeBody</button>
<table id="stable" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script type="text/javascript">
function sortTable()
{
var x = document.getElementById("stable");
var z = document.getElementById("stable").rows.length;
var rows = x.rows;
var rowLength = rows.length;
var arr = [];
for (var i = 0; i < rowLength; i++)
{
var cells = rows[i].cells;
var cLength = cells.length;
arr[i] = [];
for(var j = 0; j < cLength; j++)
{
arr[i][j] = cells[j].innerHTML;
}
}
arr.sort(function(a,b){
if(a[0] > b[0])
return 1;
if(a[0] < b[0])
return -1;
return 0;
});
// Первый вариант (не очень)
/*var output = "";
for(var i = 0; i < arr.length; i++)
{
//arr[i] = "<td>"+arr[i].join("</td><td>")+"</td>";
output += "<tr>";
for(var j = 0; j < arr[i].length; j++)
{
arr[i][j] = "<td>" + arr[i][j] + "</td>";
output += arr[i][j];
}
output += "</tr>";
}
document.getElementById("stable").innerHTML = output;
*/
// Второй вариант (лучше)
for(var i = 0; i < arr.length; i++)
{
arr[i] = "<td>"+arr[i].join("</td><td>")+"</td>";
}
document.getElementById("stable").innerHTML = "<tr>"+arr.join("</tr><tr>")+"</tr>";
}
</script>
</body>