如何让jQuery表格过滤功能排除表头<th>元素?
表格过滤时排除表头的解决方案
问题描述
执行表格过滤时,输入关键词(比如“John”)表头会跟着消失,尝试用not()方法无效,且受渲染限制无法将id="myTable"移到tbody上。
问题原因
原代码里的选择器$("#myTable tr:not('th')")逻辑错误:th是tr的子元素,不是tr本身,这个选择器根本无法排除表头所在的tr。
修正方案
有两种简单方式可以保留表头,只过滤数据行:
方法一:选择tbody内的行(推荐)
浏览器会自动为未显式声明tbody的表格生成该标签,直接选择tbody内的tr就能精准过滤数据行:
$(document).ready(function() { $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); // 仅对tbody中的表格行执行过滤 $("#myTable tbody tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); }); }); });
方法二:排除thead下的tr
如果需要更明确的排除逻辑,也可以用:not选择器直接排除表头行:
$(document).ready(function() { $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); // 排除thead中的表头行 $("#myTable tr:not(thead tr)").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1); }); }); });
完整可运行代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script> <body> <h2>可过滤表格</h2> <p>尝试搜索名字、姓氏或邮箱:</p> <input id="myInput" type="text" placeholder="搜索.."> <br><br> <table id="myTable"> <thead> <tr> <th>名字</th> <th>姓氏</th> <th>邮箱</th> </tr> </thead> <tr> <td>John</td> <td>Doe</td> <td>john@example.com</td> </tr> <tr> <td>Mary</td> <td>Moe</td> <td>mary@mail.com</td> </tr> <tr> <td>July</td> <td>Dooley</td> <td>july@greatstuff.com</td> </tr> <tr> <td>Anja</td> <td>Ravendale</td> <td>a_r@test.com</td> </tr> </table> </body>
CSS
table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; }
内容的提问来源于stack exchange,提问作者Shane S
相关产品推荐
相关产品推荐

