我想提供一个包含过滤器输入的表格,用户应输入任何数字,并在表格下方显示最接近发现的行。如何使用Javascript或Jquery遍历表中的每个TD和TR?
可以说我想用11847搜索,它没有显示任何东西,但它应该显示该行。
下面是一个工作片段和我的Html和JS到目前为止。但它只会通过第一列循环。我知道这是根据这段代码:
td = tr[i].getElementsByTagName("td")[0];
但还没有想通了如何完成这件事。
function reservationListFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("reservationListInput");
filter = input.value.toUpperCase();
table = document.getElementById("reservationTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
#reservationListInput {
background-image: url('./assets/bootstrap/fonts/searchicon.png');
/* Add a search icon to input */
background-position: 10px 12px;
/* Position the search icon */
background-repeat: no-repeat;
/* Do not repeat the icon image */
width: 100%;
/* Full-width */
font-size: 16px;
/* Increase font-size */
padding: 12px 20px 12px 40px;
/* Add some padding */
border: 1px solid #ddd;
/* Add a grey border */
margin-bottom: 12px;
/* Add some space below the input */
}
#reservationTable {
border-collapse: collapse;
/* Collapse borders */
width: 100%;
/* Full-width */
border: 1px solid #ddd;
/* Add a grey border */
font-size: 18px;
/* Increase font-size */
}
#reservationTable th,
#reservationTable td {
text-align: left;
/* Left-align text */
padding: 12px;
/* Add padding */
}
#reservationTable tr {
/* Add a bottom border to all table rows */
border-bottom: 1px solid #ddd;
}
#reservationTable tr.header,
#reservationTable tr:hover {
/* Add a grey background color to the table header and on hover */
background-color: #f1f1f1;
}
<input class="form-control" type="text" id="reservationListInput" onkeyup="reservationListFunction()" placeholder="Search for reservation..">
<table id="reservationTable">
<tr class="header">
<th style="width:40%;">Name</th>
<th style="width:20%;">Cabin</th>
<th style="width:20%;">Table</th>
<th style="width:20%;">Status</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>49222</td>
<td>201</td>
<td>Expected</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>12846</td>
<td>300</td>
<td>Inhouse</td>
</tr>
<tr>
<td>Island Trading</td>
<td>11847</td>
<td>234</td>
<td>Cancelled</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>9876</td>
<td>253</td>
<td>Partial</td>
</tr>
</table>
问题是你只在第一个td检查。 –