如何修改代码实现通过类名查找表格列(替代文本匹配)
修改搜索逻辑:从匹配TD文本到匹配TD的Class属性
Alright, let's adjust your code to search by <td> class instead of text content. Here's how you can modify it step by step:
核心修改思路
Your original code calls a search() function that looks for text inside <td> elements. We need to rewrite that function to check if a <td> has the class matching your search input instead.
修改后的完整代码
$(".searchbox").on('keyup', function () { if ($(this).val() != '') { search(this); } else { $(".data").show(); $.each($(".searchbox"), function () { if ($(this).val() != '') { $(this).keyup(); } }); } }); // Updated search function to match TD class attributes function search(input) { const searchValue = $(input).val().trim(); // Hide all rows first $(".data").hide(); // Find TDs with the matching class, then show their parent row $(".data td").filter(function() { // Use hasClass() for reliable check (works even if TD has multiple classes) return $(this).hasClass(searchValue); // Optional: If you need EXACT class match (no extra classes), use this instead: // return $(this).attr('class') === searchValue; }).closest(".data").show(); }
关键修改点解释
filter()逻辑替换:- Instead of checking the text inside
<td>, we now usehasClass(searchValue)to verify if the<td>contains the class you entered in the search box. This is the most reliable method because it accounts for elements with multiple classes (e.g.,<td class="priority-high active">). - If you need an exact match (where the
<td>'s class attribute is exactly equal to your search input, no extra classes), swap outhasClass()with$(this).attr('class') === searchValue.
- Instead of checking the text inside
忽略大小写(可选):
If you want the search to be case-insensitive, adjust the filter logic like this:return $(this).attr('class')?.toLowerCase().includes(searchValue.toLowerCase());The
?.operator prevents errors if a<td>has no class attribute.
内容的提问来源于stack exchange,提问作者KDJ
相关产品推荐
相关产品推荐

