【问题标题】:jquery live search and pagination combinedjquery实时搜索和分页相结合
【发布时间】:2018-08-25 14:14:37
【问题描述】:

我有一个简单的问题,但对于即使是基本 js 的人来说,这就是火箭科学。我已经下载了两个非常基本的脚本:一个是实时搜索,另一个是分页脚本。它们都作用于包含一些数据的表。一切都按预期工作,除了当我删除搜索词时,而不是恢复到分页表,我会看到所有记录。使用的脚本在这里:

https://www.codexworld.com/jquery-live-search-filter-on-html-table/

https://github.com/wikiti/jquery-paginate

它们非常适合我的简单应用程序,但我不知道如何在删除搜索词后使表格恢复为分页表格。这是我使用的代码:

<script>    
$(document).ready(function(){
    $('.dataSearch').on('keyup',function(){
        var searchTerm = $(this).val().toLowerCase();
        $('#carriersTable tbody tr').each(function(){
            var linestr = $(this).text().toLowerCase();
            if(linestr.indexOf(searchTerm) === -1){
                $(this).hide();
            }else{
                $(this).show();
            }
        });
    });
});

$('#carriersTable').paginate({ limit: 2 });
</script>

我尝试移动最后一行(所有可能的组合),但每次搜索都会生成无数分页链接:)。

谢谢!

【问题讨论】:

    标签: jquery search pagination combinations


    【解决方案1】:

    这是一个建议。它可能会被优化,但它显示了这个想法。

    <script>    
    $(document).ready(function(){
        $('.dataSearch').on('keyup',function() {
            // Get the search searchTerm
            var searchTerm = $(this).val().toLowerCase();
    
            // Prepare a "state" array to store rows you need to get back to
            var state = [];
    
            // Use the each loop with "key" as index iterator parameter
            $('#carriersTable tbody tr').each(function(key, value) {
                var linestr = $(this).text().toLowerCase();
                if (linestr.indexOf(searchTerm) === -1) {
                    $(this).hide();
                } else {
                    // Here you store the row in state variable since you want to show it later
                    state.push($(this));
    
                    // Show the row for the current display
                    $(this).show();
                }
            });
    
            // Now, you have a state var containing all the rows previously shown
            console.log(state);
    
            // You can create an event to detect when the search box is empty, and restore the state
            if (searchTerm.length == 0) {
                // Then you restore the state array after turning it into a string
                var restored = state.join('');
    
                // Empty the table and add the string
                $('#carriersTable').empty().append(restored);
    
                // You might need to refresh your pagination here, depends on your plugin :)
            }
        });
    });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2019-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多