我有一个javascript对象数组:
var json= [
{
"name": "xyz",
"pay": 40,
"rate": 5000,
"totals": 50000
},
{
"name": "abc",
"pay": 30,
"rate": 1400,
"totals": 100000
}
];
我已经能够成功地在javascript中的表中设置它:
var mytable = $('<table></table>').attr({ id: "myTable" });
var rows = Object.keys(dataSet).length;
var cols = dataSet.length;
var tr = [];
for (var i = 0; i < rows; i++) {
var row = $('<tr></tr>').appendTo(mytable);
row.
append($('<td>').text(json[i].name)).
append($('<td>').text(json[i].pay)).
append($('<td>').text(json[i].rate)).
append($('<td>').text(json[i].totals)).appendTo(mytable);
}
$('body').append(mytable);
function sortTable(){
var $table = $('#myTable');
console.log($table);
var $rows = $('tbody > tr',$table);
$rows.sort(function(a, b){
var keyA = $('td',a).text();
var keyB = $('td',b).text();
return (keyA > keyB) ? 1 : 0;
});
$.each($rows, function(index, row){
$table.append(row);
});
} //this just sorts name alphabetically
但我需要在desc顺序中对某些列进行排序,并在初始加载时按asc顺序排序。
名称应按字母顺序排序,按升序付费和评分,按降序排列。我无法找到正确的方法,我不能使用jquery tablesorter。
任何帮助将不胜感激。
答案 0 :(得分:0)
在创建表格之前对数据进行排序:
function compareRow(a, b) {
if (a.name != b.name) {
return a.name > b.name ? 1 : -1; // Ascending by name
}
if (a.pay != b.pay) {
return a.pay - b.pay; // Ascending by pay within same name
}
if (a.rate != b.rate) {
return a.rate - b.rate; // Ascending by rate within same name and pay
}
return b.totals - a.totals; // Descending by totals within same name, pay, and rate
}
json.sort(compareRow);