上述代码只能显示第一条符合搜索条件的结果,我需要能够显示所有符合条件的结果,另外,请再添加一个搜索按钮。
时间: 2024-04-16 08:28:19 浏览: 12
感谢您的反馈!为了显示所有符合条件的结果,并添加搜索按钮,我们可以对代码进行一些修改。以下是更新后的示例代码:
HTML部分:
```html
<input type="text" id="searchInput" placeholder="输入搜索关键字">
<button id="searchButton">搜索</button>
<table id="dataTable">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>职业</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>25</td>
<td>工程师</td>
</tr>
<tr>
<td>李四</td>
<td>30</td>
<td>设计师</td>
</tr>
<tr>
<td>王五</td>
<td>28</td>
<td>销售员</td>
</tr>
</tbody>
</table>
```
JavaScript部分:
```javascript
const searchInput = document.getElementById('searchInput');
const searchButton = document.getElementById('searchButton');
const dataTable = document.getElementById('dataTable');
searchButton.addEventListener('click', function() {
searchTable();
});
searchInput.addEventListener('input', function() {
searchTable();
});
function searchTable() {
const searchKeyword = searchInput.value.toLowerCase();
const rows = dataTable.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
const cells = rows[i].getElementsByTagName('td');
let found = false;
for (let j = 0; j < cells.length; j++) {
const cellValue = cells[j].innerText.toLowerCase();
if (cellValue.includes(searchKeyword)) {
found = true;
break;
}
}
if (found) {
rows[i].style.display = '';
} else {
rows[i].style.display = 'none';
}
}
}
```
在这个更新后的代码中,我们添加了一个搜索按钮,并为其绑定了点击事件。我们还将搜索逻辑封装在名为`searchTable`的函数中,并在输入框的`input`事件和搜索按钮的点击事件中都调用了这个函数。
这样,无论用户是在输入框中输入关键字还是点击搜索按钮,都会触发搜索逻辑。并且,所有符合条件的结果都会显示出来,而不仅仅是第一个符合条件的结果。
希望这次更新后的代码能满足您的需求!如果还有其他问题,请随时提问。