Sort a mixed data column with tablesorter

不羁岁月 提交于 2019-12-11 06:31:03

问题


I'm currently using the JQuery Tablesorter plugin found here: http://www.tablesorter.com, and I'm having trouble with a column that contains both dates and text. Here's the jsfiddle:

http://jsfiddle.net/M3V4U/1/

If you click on the first name field title, it won't sort because there's a random date inside. I tried forcing a text sort but it wouldn't work. Anyone have any ideas?


回答1:


It looks like you're trying to set the sorter type using meta data

<th class="{sorter: 'text'}">first name</th>

But the metadata plugin wasn't loaded in that demo. So either load the metadata plugin, or add the sorter type to the header option:

$("table").tablesorter({
  headers: {
    0: { sorter: "text" },
    4: { sorter: "percent" }
  }
});

Here's an updated demo.




回答2:


Found a not so great answer, but that works for now.

I removed this parser:

ts.addParser({
    id: "shortDate",
    is: function (s) {
        return /\d{1,2}[\/\-]\d{1,2}[\/\-]\d{2,4}/.test(s);
    }, format: function (s, table) {
        var c = table.config;
        s = s.replace(/\-/g, "/");
        if (c.dateFormat == "us") {
            // reformat the string in ISO format
            s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$1/$2");
        } else if (c.dateFormat == "uk") {
            // reformat the string in ISO format
            s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})/, "$3/$2/$1");
        } else if (c.dateFormat == "dd/mm/yy" || c.dateFormat == "dd-mm-yy") {
            s = s.replace(/(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{2})/, "$1/$2/$3");
        }
        return $.tablesorter.formatFloat(new Date(s).getTime());
    }, type: "numeric"
});

which seems to fix my issue, since it stops the date parser from executing altogether. This would probably cause issues in other scenarios, but seems to work for my page for now. I'm still open to any other answers, if people have them.



来源:https://stackoverflow.com/questions/12900059/sort-a-mixed-data-column-with-tablesorter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!