2 回答

TA貢獻(xiàn)1883條經(jīng)驗 獲得超3個贊
看起來您正在查詢錯誤的元素
document.querySelectorAll('td').forEach((row) => {
我想你想查詢行
document.querySelectorAll('tr').forEach((row) => {
否則,無論最后一列的結(jié)果如何,您都將覆蓋您的班級更改
(并且顯然將類應(yīng)用于 tr 而不是 tr 的父級)

TA貢獻(xiàn)1829條經(jīng)驗 獲得超6個贊
您的代碼實際上正在遍歷所有元素,但最后一列的更改覆蓋了前一列的更改。
假設(shè)您搜索了dow,第 2 行第 4 列匹配并顯示父行,但之后您的循環(huán)轉(zhuǎn)到不匹配的第 2 行第 5 列并隱藏父行。
我已經(jīng)更新了您的代碼,如下所示,您應(yīng)該遍歷行,檢查其任何列是否匹配,并根據(jù)結(jié)果僅更新該行一次。
const phonelist = document.querySelector('table');
const searchInput = document.querySelector('#search');
const searchResult = document.querySelector('#search-result');
const searchValue = document.querySelector('#search-value');
// EVENTS
function initEvents() {
searchInput.addEventListener('keyup', filter);
}
function filter(e) {
let text = e.target.value.toLowerCase();
console.log(text);
// SHOW SEARCH-RESULT DIV
if (text != '') {
searchValue.textContent = text;
searchResult.classList.remove('hidden');
} else {
searchResult.classList.add('hidden');
}
document.querySelectorAll('tr').forEach(row => {
let foundMatch = false;
row.querySelectorAll('td').forEach(col => {
let item = col.textContent.toLowerCase();
foundMatch = foundMatch || item.indexOf(text) > -1;
});
if (foundMatch) {
row.style.display = 'table-row';
} else {
row.style.display = 'none';
}
});
}
// ASSIGN EVENTS
initEvents();
<input id="search" />
<div class="phonelist">
<div id="search-result" class="hidden">
<p>Search results for <b id="search-value"></b>:</p>
</div>
<table class="striped">
<thead>
<tr>
<th>Phone</th>
<th>Fax</th>
<th>Room</th>
<th>Name</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>165</td>
<td>516</td>
<td>1.47</td>
<td>Johnathan Doe</td>
<td>Sales</td>
</tr>
<tr>
<td>443</td>
<td>516</td>
<td>1.47</td>
<td>Jane Dow</td>
<td>Development</td>
</tr>
</tbody>
</table>
</div>
添加回答
舉報