我在 Bootstrap 表中添加了一個搜索框。所以添加的第一件事是這個輸入,它作業正常,但我需要搜索Country names 而不是Names。
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
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) {
txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
</table>
uj5u.com熱心網友回復:
td = tr[i].getElementsByTagName("td")[1];- 我建議你只搜索 tbody
- 也使用事件偵聽器
document.getElementById("myInput").addEventListener("keyup",function() {
// Declare variables
const filter = this.value.toUpperCase();
const trs = document.querySelectorAll("#myTable tbody tr");
// Loop through all table rows, and hide those who don't match the search query
trs.forEach(tr => {
const td = tr.cells[1];
txtValue = td.textContent.toUpperCase()
tr.hidden = txtValue && !txtValue.includes(filter)
})
});
<input type="text" id="myInput" placeholder="Search for names.." autocomplete="off">
<table id="myTable">
<thead>
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Microsoft</td>
<td>USA</td>
</tr>
</tbody>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344971.html
標籤:javascript html 推特引导 html-table twitter-bootstrap-3
上一篇:當該頁面有<iframe>時,我想動態地將css類添加到正文中,并希望在其他頁面中沒有<iframe>時洗掉該類
