查找列并应用自定义解析器

时间:2011-03-07 12:59:33

标签: jquery sorting tablesorter

我正在使用tablesorter插件来做一些非常有效的自定义排序。我将此解析器设置为特定列,但应用程序允许我通过某些设置打开和关闭列,因此根据设置,此自定义排序列的索引可能会有所不同。

是否可以让它自动找到正确的列并使用我得到的解析器方法?而不是手动将其放在标题索引上。

编辑,现在我正在使用它(有时“宿舍”分拣机可以在另一个索引,所以我需要代码自动检测它)

$("table").tablesorter({
                headers: {
                    0: { sorter: false },
                    1: { sorter: false },
                    5: { sorter: "quarters" }
                }
            });

我的自定义解析器:

$.tablesorter.addParser({
        id: 'quarters',
        is: function (s) {
            return false;
        },
        format: function (s) {
            var match = s.match(/(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20\d\d)/);
            if (match)
            {
               return match[3] * 1000 - match[2] * 100 - match[1] * 10;                
            }
            else return 0;
        },
        type: 'text'
    });

2 个答案:

答案 0 :(得分:1)

如果th上有某个选择器要应用quarters分拣机,则可以使用jQuery选择该标头,然后使用prevUtil获取所有它之前的th兄弟节点,并使用该大小来确定所需列的索引。

我的示例假设您的相关列有id quarters

var headerPosition = $("#quarters").prevUntil().size());
var headers = {};

headers[headerPosition] = "quarters";

$("table").tablesorter({
    headers: headers
});

这是一个jsfiddle:

http://jsfiddle.net/magicaj/7A3ZF/1/

答案 1 :(得分:0)

您可以使用此小函数来搜索要使用排序解析器的标头的索引:

function get_index_by_text($list, text){
    var searched = -1;
    $list.each(function(index){
        if ($(this).text() == text) {
            searched = index;
            return(false);
        }
    });
    return(searched);
}

var quarters_index = get_index_by_text($("table thead th"), "quarters");

请注意并检查文本是否已找到,如果不是该函数将返回-1。