带有自定义匹配函数的表排序程序选择框



我有一个带有一列的HTML表,其中存在一个无序的字符串列表。我正在使用筛选插件与列表交互的tablesorter。我希望列的所有单元格中的每个字符串都存在于表头的选择过滤器中。如果用户选择了一个选项,应该显示这些行,其中该字符串出现在特定列单元格的无序列表中。

让我给你举个例子。我有以下清单:

<table>
    <thead>
        <tr>
            <th>name</th>
            <th>profession</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Carl</td>
            <td>
                <ul>
                    <li>Builder</li>
                    <li>Professor</li>
                </ul>
            </td>
        </tr>
        <tr>
            <td>Lisa</td>
            <td>
                <ul>
                    <li>Programmer</li>
                    <li>Professor</li>
                </ul>
            </td>
        </tr>
    </tbody>
</table>

在表头中,我希望tablesorter显示一个包含三个专业的选择框。如果选择了professor,则应该显示这两行。如果选择programmer,则只显示Lisa。我怎么才能做到呢?

使用filter_functions小部件选项如下(演示):

$(function () {
    $('table').tablesorter({
        theme: 'blue',
        widgets: ['filter'],
        widgetOptions: {
            filter_functions: {
                1: {
                    "Programmer": function (e, n) { return /programmer/.test(n); },
                    "Professor" : function (e, n) { return /professor/.test(n); },
                    "Builder"   : function (e, n) { return /builder/.test(n); } 
                }
            }
        }
    });
});

更新:如果您不想硬编码,因为专业不同,那么您可以使用filter_selectSource选项抓取所有列文本,从列表中提取出每个项目,然后将其作为数组返回(演示):

HTML(确保包含这些类名)

<th class="filter-select filter-match">profession</th>
脚本

$(function () {
    $('table').tablesorter({
        theme: 'blue',
        widgets: ['filter'],
        widgetOptions: {
            filter_selectSource: function (table, column, onlyAvail) {
                // get an array of all table cell contents for a table column
                var arry = [],
                    array = $.tablesorter.filter.getOptions(table, column, onlyAvail);
                // split content if multiple professions are encountered
                $.each( array, function(i, n){
                    // look for carriage returns; split into two separate professions
                    if (/n/.test(n)) {
                        n = n.split(/n/);
                    }
                    arry.push(n);
                });
                // flatten array
                return $.map(arry, function(n){ return n; });
            }
        }
    });
});

最新更新