当单元格包含嵌套表时,如何对表行进行排序? [英] How to sort table rows when cells contain nested tables?

查看:75
本文介绍了当单元格包含嵌套表时,如何对表行进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此jQuery代码向表添加排序功能(根据列中的值更改顺序):

I am using this jQuery code to add sorting (changing order based on values in a column) functionality to tables:

$('th.sortBy').click(function(){
    var table = $(this).parents('table').eq(0);
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));
    this.asc = !this.asc;
    if (!this.asc){rows = rows.reverse()};
    for (var i = 0; i < rows.length; i++){table.append(rows[i])};
});

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index);
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
    };
};

function getCellValue(row, index){ return $(row).children('td').eq(index).html(); };

但是,在单元格包含另一个表的表上,排序会破坏所有内容-它需要所有表行(包括嵌套表),并对所有表行重新排序.当然,我需要嵌套的行保留在表中,并且不要在另一个不相关的级别上进行排序.

However, on a table where cells contain another table, the sorting breaks all - it takes all of the table rows including the nested and reorders them all. I, of course, need the nested rows to stay within their tables and not get sorted on another, unrelated level.

该如何解决此问题?

我尝试更改

var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()));

var rows = table.children('tr:gt(0)').toArray().sort(comparer($(this).index()));

,但它仍会选择并排序所有行,包括嵌套行.

but it still selects and orders all of the rows, including nested ones.

推荐答案

问题是.findrows变量中得到 ALL tr(除了第一个变量,因为:gt(0)),甚至是嵌套表中的内容.

The problem is that .find is getting ALL tr in the rows var (except the very first, because of :gt(0)), even those in a nested table.

基于该解释,我唯一可以建议的是在第二级使用类tr s ...
因此,您可以使用.not()对其进行过滤.

The only thing I can suggest, based on that examble, is to use a class on the second level trs...
So you can filter them using .not().

$('th.sortByOK').click(function(){
    var table = $(this).parents('table').eq(0);
    var rows = table.find("tr:gt(0)").not(".secondLevel").toArray().sort(comparer($(this).index()));
    this.asc = !this.asc;
    if (!this.asc){rows = rows.reverse()};
    for (var i = 0; i < rows.length; i++){table.append(rows[i])};
});

CodePen
希望能有所帮助.

CodePen
Hoping it helps.

这篇关于当单元格包含嵌套表时,如何对表行进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆