如何利用html和js写一个可搜索的搜索框
时间: 2024-04-30 13:23:12 浏览: 11
1. 首先,在HTML中创建一个搜索框的元素,可以使用<input>标签,并设置type属性为text。
2. 然后,添加一个按钮,使用户可以点击按钮来执行搜索操作。按钮可以使用<button>标签来创建。
3. 在JavaScript中,获取搜索框和按钮的元素,并添加一个事件监听器,监听按钮的点击事件。
4. 在事件监听器中,获取搜索框中的文本,并使用它来执行搜索操作。可以使用JavaScript中的数组过滤方法来过滤搜索结果。
5. 在HTML中,使用<ul>和<li>标签来显示搜索结果列表。可以使用JavaScript中的DOM操作来创建和更新这些元素。
以下是一个简单的示例代码:
HTML:
```
<input type="text" id="search-box" placeholder="Search...">
<button id="search-btn">Search</button>
<ul id="results"></ul>
```
JavaScript:
```
const searchBox = document.querySelector('#search-box');
const searchBtn = document.querySelector('#search-btn');
const resultsList = document.querySelector('#results');
searchBtn.addEventListener('click', () => {
const searchText = searchBox.value.toLowerCase();
const filteredResults = data.filter(item => {
return item.name.toLowerCase().includes(searchText);
});
displayResults(filteredResults);
});
function displayResults(results) {
resultsList.innerHTML = '';
results.forEach(item => {
const li = document.createElement('li');
li.textContent = item.name;
resultsList.appendChild(li);
});
}
```
在这个例子中,我们使用一个名为data的数组来存储搜索结果。在搜索按钮点击事件中,我们获取搜索框中的文本,并使用它来过滤数组并显示结果。在displayResults函数中,我们使用DOM操作来创建<li>元素,并将其添加到<ul>中显示搜索结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)