好的,所以我非常接近这里。这个排序函数适用于常规HTML表,但是当我尝试使用getJson加载我的表时它不起作用,我希望这是由于我在jQuery和JS领域缺乏知识。希望我没有完全走错路。这是代码。提前谢谢!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<div id="catTable"></div>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
var TableIDvalue = "indextable";
var TableLastSortedColumn = -1;
function SortTable() {
var sortColumn = parseInt(arguments[0]);
var type = arguments.length > 1 ? arguments[1] : 'T';
var dateformat = arguments.length > 2 ? arguments[2] : '';
var table = document.getElementById(TableIDvalue);
var tbody = table.getElementsByTagName("tbody")[0];
var rows = tbody.getElementsByTagName("tr");
var arrayOfRows = new Array();
type = type.toUpperCase();
dateformat = dateformat.toLowerCase();
for(var i=0, len=rows.length; i<len; i++) {
arrayOfRows[i] = new Object;
arrayOfRows[i].oldIndex = i;
var celltext = rows[i].getElementsByTagName("td")[sortColumn].innerHTML.replace(/<[^>]*>/g,"");
if( type=='D' ) { arrayOfRows[i].value = GetDateSortingKey(dateformat,celltext); }
else {
var re = type=="N" ? /[^\.\-\+\d]/g : /[^a-zA-Z0-9]/g;
arrayOfRows[i].value = celltext.replace(re,"").substr(0,25).toLowerCase();
}
}
if (sortColumn == TableLastSortedColumn) { arrayOfRows.reverse(); }
else {
TableLastSortedColumn = sortColumn;
switch(type) {
case "N" : arrayOfRows.sort(CompareRowOfNumbers); break;
case "D" : arrayOfRows.sort(CompareRowOfNumbers); break;
default : arrayOfRows.sort(CompareRowOfText);
}
}
var newTableBody = document.createElement("tbody");
for(var i=0, len=arrayOfRows.length; i<len; i++) {
newTableBody.appendChild(rows[arrayOfRows[i].oldIndex].cloneNode(true));
}
table.replaceChild(newTableBody,tbody);
} // function SortTable()
function CompareRowOfText(a,b) {
var aval = a.value;
var bval = b.value;
return( aval == bval ? 0 : (aval > bval ? 1 : -1) );
}
$.getJSON('cats.json', function(cats) {
var output='<table id="indextable" border="1" cellpadding="10" cellspacing="0" style="border-collapse:collapse;">';
output+="<thead>"
output+="<tr>";
//output+="<th> HeadShot </th>";
output+='<th><a href=' + "javascript:SortTable(1,'T');" + '>Breed</a></th>';
output+='<th><a href=' + "javascript:SortTable(1,'T');" + '>Country</a></th>';
output+='<th><a href=' + "javascript:SortTable(1,'T');" + '>CoffeePreference</a></th>';
output+="</tr>";
output+="</thead>"
for (var i in cats) {
output+="<tbody>"
output+="<tr>";
//output+="<td><img src='" + cats[i].picture+"' alt='cat picture'></td>"
output+="<td>" + cats[i].breed + "</td>"
output+="<td>" + cats[i].country + "</td>"
output+="<td>" + cats[i].coffeePreference + "</td>"
output+="</tr>";
output+="</tbody>"
}
output+="</table>";
document.getElementById("catTable").innerHTML=output;
});
</script>
</body>
</html>