javascript - 将新的过滤器功能与现有分页合并并过滤 jQuery/Javascript

标签 javascript jquery filter pagination

I'm having a problem with my new table filtering function, the problem happens when selecting an offer to filter by - rather than showing the rows from all the filterable data inside the table the filter filters the visible rows only minus the data通过分页隐藏。

最重要的是,当我单击“更多”以显示更多行时,表格开始显示当前过滤器之外的数据。这不好。

我还有另一个过滤功能,可以按“免费手机”进行过滤,该功能已与我的分页方法(下面的代码)结合使用。

我如何将这个过滤器(下拉菜单)与我的“免费手机”过滤器(复选框一个)和分页方法合并,这样当我选择一个选项进行过滤时,过滤器会处理表格中的所有数据而不仅仅是分页显示的可见行。

https://jsfiddle.net/51Le6o06/48/

上面的 fiddle 显示了两个过滤函数并排工作,但它们不能很好地协同工作。

正如您在上面的 jsfiddle 中看到的那样,下拉过滤器从 HTML 中收集它的选项,然后将它们显示在下拉菜单中,因此所有选项都在那里被过滤,只是被分页隐藏了。

这是每个函数的 jQuery 和 Javascript。

这是新过滤器,但效果不佳。

$(document).ready(function() {
    $('.filter-gift').each(filterItems);
});

function filterItems(e) {
    var items = [];
    var table = '';
    tableId = $(this).parent().parent().attr('tag')

      var listItems = "";
        listItems += "<option value=''> -Select- </option>";
        $('div[tag="' + tableId + '"] table.internalActivities .information').each(function (i) {
            var itm = $(this)[0].innerText;
            if ($.inArray(itm, items) == -1) {
                items.push($(this)[0].innerText);
                listItems += "<option value='" + i + "'>" + $(this)[0].innerText + "</option>";
            }
        });

    $('div[tag="' + tableId+ '"] .filter-gift').html(listItems);

    $('.filter-gift').change(function () {
    if($(this).val()!= "") {
        var tableIdC = $(this).parent().parent().attr('tag');

        var text = $('div[tag="' + tableIdC + '"] select option:selected')[0].text.replace(/(\r\n|\n|\r| |)/gm, "");;
            $('div[tag="' + tableIdC + '"] .product-information-row').each(function (i) {
                if ($(this).text().replace(/(\r\n|\n|\r| |)/gm, "") == text) {
                    $(this).show();
                    $(this).prev().show();
                    $(this).next().show();
                }
                else {
                    $(this).hide();
                    $(this).prev().hide();
                    $(this).next().hide();
                }
            }); 
            } else {
            $(this).parent().parent().find('table tr').show();
            }
        });     
}

这是我要与上述功能(有效)合并的过滤器和分页功能。

jQuery.fn.sortPaging = function(options) {
    var defaults = {
        pageRows: 2
    };
    var settings = $.extend(true, defaults, options);
    return this.each(function() {

        var container = $(this);
        var tableBody = container.find('.internalActivities > tbody');
        var dataRows = [];
        var currentPage = 1;
        var maxPages = 1;
        var buttonMore = container.find('.seeMoreRecords');
        var buttonLess = container.find('.seeLessRecords');
        var buttonFree = container.find('.filter-free');
        var tableRows = [];
        var maxFree = 0;
        var filterFree = buttonFree.is(':checked');
        function displayRows() {
            tableBody.empty();
            var displayed = 0;
            $.each(dataRows, function(i, ele) {
                if( !filterFree || (filterFree && ele.isFree) ) {
                    tableBody.append(ele.thisRow).append(ele.nextRow);
                    displayed++;
                    if( displayed >= currentPage*settings.pageRows ) {
                        return false;
                    };
                };
            });
        };
        function checkButtons() {
            buttonLess.toggleClass('element_invisible', currentPage<=1);
            buttonMore.toggleClass('element_invisible', filterFree ? currentPage>=maxFreePages : currentPage>=maxPages);
        };
        function showMore() {
            currentPage++;
            displayRows();
            checkButtons();
        };
        function showLess() {
            currentPage--;
            displayRows();
            checkButtons();
        };
        function changedFree() {
            filterFree = buttonFree.is(':checked');
            if( filterFree && currentPage>maxFreePages ) {
                currentPage=maxFreePages;
            };
            displayRows();
            checkButtons();
        };

        tableBody.find('.product-data-row').each(function(i, j) {
            var thisRow = $(this);
            var nextRow = thisRow.next();
            var amount = parseFloat(thisRow.find('.amount').text().replace(/£/, ''));
            var isFree = thisRow.find('.free').length;
            maxFree += isFree;
            dataRows.push({
                amount: amount,
                thisRow: thisRow,
                nextRow: nextRow,
                isFree: isFree
            });
        })

        dataRows.sort(function(a, b) {
            return a.amount - b.amount;
        });
        maxPages = Math.ceil(dataRows.length/settings.pageRows);
        maxFreePages = Math.ceil(maxFree/settings.pageRows);

        tableRows = tableBody.find("tr");

        buttonMore.on('click', showMore);
        buttonLess.on('click', showLess);
        buttonFree.on('change', changedFree);

        displayRows();
        checkButtons();

    })

};

$('.sort_paging').sortPaging();

目标

  • 使过滤器与分页一起工作。
  • 使过滤器与“Free Handset”过滤器同时工作。

最佳答案

您的代码不必要地复杂。尝试将其分解为必要的步骤。关于您的基本问题:一次完成所有事情(阅读下文以充分理解我的方法):

function onFilterChange() {
    filterProducts();
    resetPagination();
    showNextPage();
}

同时改进你的数据结构:

如果您使用 html 作为数据源,请在主要对象中使用属性,这将使查找它们变得容易。使用多个 tbody 标签对您的 trs 进行分组:

<tbody freeTv='false' freeHandset='false' cost='200'>
    <tr>
        <td>content of product 1</td>
    </tr>
    <tr>
        <td>description of product 1</td>
    </tr>
</tbody>
<tbody freeTv='true' freeHandset='false' cost='300'>
    <tr>
        <td>content of product 2</td>
    </tr>
    <tr>
        <td>description of product 2</td>
    </tr>
</tbody>

我更喜欢将类添加到我的元素中,而不是删除/添加整个元素。请注意,如果您打算使用 nth-css-styling,这会造成困惑。如果您不需要它,这是添加交互的一种很好的、​​可调试的方式:

function filterProducts() {
    $('tbody').addClass('filtered');
    // ... some domain-specific magic here ...
    $('tbody[freeTv="true"]').removeClass('filtered');
}

现在您只需要一个 .filtered CSS 定义,例如:

.filtered { display: none; }

对于分页,您可以采用类似的方式。首先隐藏所有内容(再次使用 css .paged { display: none; } ):

function resetPagination() {
    $('tbody').addClass('paged');
    $('tbody.filtered').removeClass('paged');
}

然后显示你想要的(前 10 个分页的):

function showNextPage() {
    $('tbody.paged').slice(0, 10).removeClass('paged');
}

https://jsfiddle.net/g9zt0fan/

关于javascript - 将新的过滤器功能与现有分页合并并过滤 jQuery/Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37105299/

相关文章:

javascript - 选择下拉元素后保持下拉列表打开

javascript - 在文本区域中输入时检测新行

javascript - 当我向上滚动时,导航栏必须停留在顶部位置并且不要通过跟随导航栏图像隐藏

php - 从文件夹中删除与记录关联的图像

python - Python 中长列表的高效过滤、映射和归约操作

arrays - 通过唯一字典值过滤字典数组的简洁方法

javascript - 未捕获的语法错误 : Unexpected token ( error

javascript - JsDoc:将参数类型定义为来自外部模块的类型

javascript - 在 jQuery 中将焦点设置为页面加载时的输入字段(以便用户可以开始输入)

javascript - crm2013 - 如何过滤特定实体的客户端查找