Files
ClassContent/历届学生/韩一伟/项目开发/上课项目/tabs切换/jianyi.html
2024-09-27 02:06:13 +08:00

73 lines
2.2 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>搜索建议</title>
</head>
<body>
<input type="text" placeholder="请输入关键字">
<ul>
</ul>
</body>
<script>
var search = document.querySelector("input");
// 搜索建议数组
var list = ['今天下雨了', '今天忘记吃药', '今天下雨很大', 'html很简单', 'js+html实现功能', '忘记带手机了'];
// 保存符合条件的建议
var newList = [];
// 为输入框绑定输入事件
search.oninput = function () {
// 清除上一次留下的记录
newList = []
// 用户输入的关键字不等0,表示有值才开始走里面的搜索建议代码
if (search.value.length != 0) {
// 遍历取出list中每条数据
list.forEach(function (v) {
// 判断用户输入的是否在建议数组中有
if (v.includes(search.value)) {
// 替换关键字为带标签样式的数据
// 再保存到新数组newList中
newList.push(
v.replace(search.value, `<span style="color:red">${search.value}</span>`)
)
}
})
renderLi()
// 没有输入东西,给用户一个提示
} else {
document.querySelector("ul").innerHTML = "请输入关键字"
}
}
// 专门用来生成多个li标签,并放到网页ul中
function renderLi() {
// 如果没搜到,现实暂无
if (newList.length == 0) {
document.querySelector("ul").innerHTML = "<p>暂无建议</p>"
// 搜到了
} else {
// 保存所有li标签代码的
var li = ""
// 遍历newList搜索建议数组
newList.forEach(function (v) {
// 进行拼接多个li标签
li += `<li>${v}</li>`
});
// 使用 innerHTML 将所有li标签的html代码塞入 ul
document.querySelector("ul").innerHTML = li
}
}
</script>
</html>