使用w3schools上的表格排序作为基础,如何在搜索表格时保持表格标题不会消失?
$(document).ready(function(){
$('#search-attorneys').on('keyup', function(){
var input, filter, table, tr, td, i;
input = $("#search-attorneys");
filter = $("#search-attorneys").val().toUpperCase();
table = $("#attorneys");
tr = $("tr");
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td");
var found = false;
for (j = 0; j < tds.length; j++) {
td = tds[j];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
});
});
JSFIDDLE:LINK
答案 0 :(得分:1)
你需要先改变循环: -
for (i = 1; i < tr.length; i++) { // not start with 0 start with 1.
表示离开表<thead><tr>
,然后开始搜索休息<tr>
。
注意: - 检查它,如果您遇到任何问题。我会为你创建一个例子。
答案 1 :(得分:0)
这可以通过将行放在tbody中并更改变量e tr
选择器来轻松实现。
$(document).ready(function(){
$('#search-attorneys').on('keyup', function(){
var input, filter, table, tr, td, i;
input = $("#search-attorneys");
filter = $("#search-attorneys").val().toUpperCase();
table = $("#attorneys");
tr = $("tbody tr"); // CHANGED
for (i = 0; i < tr.length; i++) {
tds = tr[i].getElementsByTagName("td");
var found = false;
for (j = 0; j < tds.length; j++) {
td = tds[j];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search-attorneys" placeholder="Search for names.." title="Type in a name">
<table id="attorneys">
<thead class="cf">
<tr>
<th class="numeric">attorney</th>
<th class="numeric">location</th>
<th class="numeric">practice area</th>
<th class="numeric">email</th>
<th class="numeric">phone</th>
</tr>
</thead>
<tbody>
<tr>
<td data-title="location">Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Italy</td>
</tr>
<tr>
<td>North/South</td>
<td>UK</td>
</tr>
<tr>
<td>Paris specialites</td>
<td>France</td>
</tr>
</tbody>
</table>
&#13;