Stuck,我需要根据每个级别的表格行中的自定义属性对表格进行排序,然后根据td本身的文本进行排序。所以对于所有级别都要经历并排序更高级别
所以我有:
<table>
<tbody>
<tr data-level="1" data-parent="0"><td>3</td></tr>
<tr data-level="1" data-parent="0"><td>1</td></tr>
<tr data-level="2" data-parent="1"><td>1b</td></tr>
<tr data-level="2" data-parent="1"><td>1c</td></tr>
<tr data-level="2" data-parent="1"><td>1a</td></tr>
<tr data-level="1" data-parent="0"><td>2</td></tr>
</tbody>
</table>
我的期望看起来像这样:
<table>
<tbody>
<tr data-level="1" data-parent="0"><td>1</td></tr>
<tr data-level="2" data-parent="1"><td>1a</td></tr>
<tr data-level="2" data-parent="1"><td>1b</td></tr>
<tr data-level="2" data-parent="1"><td>1c</td></tr>
<tr data-level="1" data-parent="0"><td>2</td></tr>
<tr data-level="1" data-parent="0"><td>3</td></tr>
</tbody>
</table>
我试过这个:
function sortMultilevel(level){
var $sort = this;
var $table = $('table');
var $rows = $('tbody > tr[data-level="'+level+'"]',$table);
$rows.sort(function(a, b){
var keyA = $('td',a).text();
var keyB = $('td',b).text();
if($($sort).hasClass('asc')){
return (keyA > keyB) ? 1 : 0;
} else {
return (keyA < keyB) ? 0 : 1;
}
});
$.each($rows, function(index, row){
$table.append(row);
});
}
function doMultilevelSort(){
if($("tr").length > 0){
$("tr").not(".sorted").each(function(){
$(this).addClass("sorted");
var level = $(this).attr("data-level");
sortMultilevel(level);
console.log("sorting: " + level);
});
}
}
doMultilevelSort(); // call the function
我可能会想到这一点。如果我是我,你就是我的学生,我很满意。欣赏一下。
答案 0 :(得分:0)
$('#sort').click(function (e) {
var $table = $('#sort_me');
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);
});
e.preventDefault();
});