给出一个html页面,对应的js以及数据文本,其中功能需求为:一个类似于百度搜索的功能,输入字符串,对应下拉框显示相关内容的列表,在下拉列表中可以选中需要的内容,其中搜索数据是从数据文本中解析出来的
时间: 2024-03-15 12:47:05 浏览: 20
HTML页面:
```html
<!DOCTYPE html>
<html>
<head>
<title>搜索框</title>
</head>
<body>
<input type="text" id="search" placeholder="输入关键词" />
<ul id="search-result"></ul>
<script src="search.js"></script>
</body>
</html>
```
JS代码:
```javascript
let data = []; // 搜索的数据
const searchInput = document.getElementById("search");
const searchResult = document.getElementById("search-result");
// 从数据文本中解析出搜索数据
fetch("data.txt")
.then((response) => response.text())
.then((text) => {
data = text.split("\n").filter((item) => item.trim() !== "");
})
.catch((error) => console.error(error));
searchInput.addEventListener("input", (event) => {
const keyword = event.target.value.trim(); // 获取输入框中的值并去除首尾空格
if (!keyword) {
searchResult.innerHTML = ""; // 关键词为空,清空下拉列表
return;
}
const matchedData = data.filter((item) =>
item.includes(keyword)
); // 过滤出匹配的数据
if (matchedData.length === 0) {
searchResult.innerHTML = "<li>无匹配结果</li>"; // 没有匹配的数据
} else {
searchResult.innerHTML = matchedData
.map((item) => `<li>${item}</li>`)
.join(""); // 根据匹配的数据渲染下拉列表
}
});
searchResult.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
searchInput.value = event.target.innerText;
searchResult.innerHTML = ""; // 选中下拉列表中的内容,清空下拉列表
}
});
```
数据文本:
```
苹果
香蕉
橙子
西瓜
葡萄
芒果
梨
草莓
柠檬
橘子
```
在输入框中输入关键词时,会根据输入的值动态显示下拉列表,并且可以通过鼠标点击下拉列表中的内容来选中。其中,搜索的数据是从数据文本中解析出来的。注意,这只是一个简单的实现示例,实际应用中可能需要更复杂的逻辑和交互效果。