如何清除Bootstrap-table的filterBy过滤器?
解决Bootstrap-table自定义过滤后无法清除过滤的问题
你遇到的问题是:使用自定义filterAlgorithm实现欧盟国家过滤后,调用filterBy({})无法清除过滤,因为自定义过滤逻辑仍在生效。
解决方案
清除过滤时,需要显式将filterAlgorithm重置为null(恢复默认过滤逻辑),同时传入空过滤器对象。修改清除按钮的点击事件代码如下:
$('#btnClearFilter').click(function() { $('#mainTable').bootstrapTable('filterBy', {}, { filterAlgorithm: null }); });
原因说明
第一次调用filterBy时传入的自定义filterAlgorithm会被保存在表格的配置中,后续仅调用filterBy({})时,表格依然会使用这个自定义算法进行过滤,导致空过滤器无法生效。只有将filterAlgorithm设为null,才能恢复默认的过滤逻辑,让所有行重新显示。
修改后的完整代码
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test</title> <link href="vendor/twbs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"> <link href="vendor/fortawesome/font-awesome/css/all.min.css" rel="stylesheet"> <link href="vendor/wenzhixin/bootstrap-table/dist/bootstrap-table.min.css" rel="stylesheet"> </head> <body> <div class="container"> <table id="mainTable" data-toggle="table" data-classes="table table-striped"> <thead> <tr> <th scope="col" data-field="USER_ID">User ID</th> <th scope="col" data-field="FIRST_NAME">First name</th> <th scope="col" data-field="LAST_NAME">Last name</th> <th scope="col" data-field="EMAIL">Email</th> <th scope="col" data-field="COUNTRY">Country</th> </tr> </thead> <tbody> <tr><td>1</td><td>John</td><td>Smith</td><td>john.smith@example.com</td><td>US</td></tr> <tr><td>2</td><td>Jane</td><td>Doe</td><td>jane.doe@example.com</td><td>ES</td></tr> <tr><td>3</td><td>Alice</td><td>Something</td><td>alice@example.com</td><td>FR</td></tr> <tr><td>4</td><td>Bob</td><td>Jones</td><td>bjonesss@example.com</td><td>UK</td></tr> </tbody> </table> <footer> <div class="row"> <div class="col"> <button type="button" class="btn btn-primary" id="btnFilterEU">EU countries only</button> <button type="button" class="btn btn-secondary" id="btnClearFilter">Clear filter</button> </div> </div> </footer> </div> <!-- JavaScript --> <script src="vendor/components/jquery/jquery.min.js"></script> <script src="vendor/twbs/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="vendor/wenzhixin/bootstrap-table/dist/bootstrap-table.min.js"></script> <script> $(function() { $('#btnFilterEU').click(function() { $('#mainTable').bootstrapTable('filterBy', {}, { 'filterAlgorithm': (row, filters) => { return ['DE', 'FR', 'ES', 'BE' /* ... */].includes(row.COUNTRY); } }); }); $('#btnClearFilter').click(function() { $('#mainTable').bootstrapTable('filterBy', {}, { filterAlgorithm: null }); }); }); </script> </body> </html>
内容的提问来源于stack exchange,提问作者Leszek Pachura
相关产品推荐
相关产品推荐

