Files
ClassContent/历届学生/zheng-yuqing/项目练习/上课项目/js案例/搜索建议.html
2024-09-27 02:06:13 +08:00

68 lines
1.5 KiB
HTML

<!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>
// 给输入框绑定 oninput 事件 ,实时获取输入框的数值
// 然后从我们内置的数组中找到匹配项
// 搜索结果的关键字 加红 表示
var input = $("input"),
keyWord = [ 'html学习', '不想学html', '学习html和css', '天气不好', '今天心情不好', 'css入门学习', '心情很好' ],
newArr = [];
input.oninput = () => {
newArr = []
if (input.value.length != 0) {
keyWord.forEach((value, index) => {
if (value.includes(input.value)) {
var newText = value.replace(input.value, `<span style="color: red">${input.value}</span>`);
newArr.push(newText)
}
});
renderPage()
} else {
$("ul").innerHTML = ""
}
}
// 将 newArr 显示到页面上
function renderPage() {
$("ul").innerHTML = ""
newArr.forEach((value, index) => {
$("ul").innerHTML += `<li>${value}</li>`
})
}
// 获取单个标签
function $(className) {
return document.querySelector(className)
}
</script>
</html>