如何解决如果搜索不匹配,如何隐藏表格?
如果表格搜索匹配隐藏所有table
元素,thead
或 tr
应自动隐藏。
我试过这个方法但没有用。
if ($("table tr:visible").length === 1) {
$("tbody").addClass('display-hide');
}
或
$(document).each(function () {
if ($("table tr:visible").length === 1) {
$("tbody").addClass('display-hide');
}
})
演示:https://jsfiddle.net/abilashu/m5k7av21/13/
如果可能,请提供演示。
解决方法
您可以使用 each
循环遍历表,然后使用 $(this).find("tbody tr:visible").length
获取表内可见 trs 的长度,然后取决于来自 tbody 或 thead 的长度 addClass
或 removeClass
。
演示代码:
class tableLiveSearch {
constructor(table,searchable) {
this.table = table;
this.searchable = searchable;
this.hide_row_list = new Array();
}
updateTable(search_query) {
this.hide_row_list = this.searchTable(search_query);
this.showAllTableRows();
this.hideTableRows();
}
searchTable(search_query) {
var temporary_list = new Array();
var $searchable_items = $(this.table + ' ' + this.searchable);
$searchable_items.each(function(index,value) {
var $this_element = $(this);
search_query = search_query.toLowerCase();
var search_content = $this_element.text().toLowerCase();
if (search_content.indexOf(search_query) == -1)
temporary_list.push($this_element.parent());
});
return temporary_list;
}
showAllTableRows() {
$(this.table + ' ' + this.searchable).each(function(index,value) {
$(this).parent().show();
});
}
hideTableRows() {
$.each(this.hide_row_list,function(index,value) {
$(this).hide();
});
}
}
var searchtable = new tableLiveSearch('.search-table','.searchable');
$('#search').keyup(function() {
searchtable.updateTable($(this).val());
//remove class from tbody and thead
$("thead,tbody").removeClass('display-hide')
//loop through table
$("table.search-table").each(function() {
//check if the length is (hide or show
$(this).find("tbody tr:visible").length == 0 ? $(this).find("thead,tbody").addClass('display-hide') : $(this).find("thead,tbody").removeClass('display-hide')
})
});
.display-hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container mt-5">
<div class="row mt-5">
<div class="col-12 mt-4">
<form class="form">
<input class="form-control" id="search" type="search" placeholder="Search a name..." aria-label="Search">
</form>
</div>
</div>
<div class="row mt-4">
<div class="col">
<table class="table search-table">
<thead>
<tr>
<th>Item Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td class="searchable">Stackoverflow</td>
<td>33</td>
</tr>
<tr>
<td class="searchable">Google</td>
<td>2</td>
</tr>
<tr>
<td class="searchable">Twitter</td>
<td>2</td>
</tr>
</tbody>
</table>
<table class="table search-table">
<thead>
<tr>
<th>Item Name</th>
<th>Cost</th>
</tr>
</thead>
<tbody>
<tr>
<td class="searchable">Apple</td>
<td>345</td>
</tr>
<tr>
<td class="searchable">Banana</td>
<td>34</td>
</tr>
<tr>
<td class="searchable">Orange</td>
<td>87</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。