Files
ClassContent/历届学生/font-end-nine/项目练习/学生项目/杨锐/js联习/搜索建议.html
2024-09-27 02:06:13 +08:00

67 lines
1.8 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>Document</title>
</head>
<body>
<input type="text" placeholder="请输入关键字">
<ul>
</ul>
</body>
<script>
var arr = ['今天天气真好', 'html学习', '不喜欢html', '热爱学习', '天气不好,是阴天', '不喜欢学习'];
//定义一个数组
var cunfang = [], input = $("input");
//定义一个空数组 以及一个变量
input.oninput = function () {
//定义一个用户在input搜索框中输入时发生事件
cunfang = []
//数组清空
if (input.vlue != 0) {
//当搜索框有有数据时
arr.forEach(function (v, i) {
//通过foreach遍历arr数组中的所有元素存放在v中,下标在i中
if (v.includes(input.vlue)) {
//通过includes判断输入时的值是否在arr数组中
var span = `<span style="color:red">${input.vlue}</span>`
cunfang.push(v.replace(input.vlue, span))
//如果在向cunfang数组添加v中的值并且使相同字符串变成红色
}
});
renderLi();
//调用renderLi函数
}
else {
$("ul").innerHTML = ""
//否则就清空
}
}
function renderLi() {
$("ul").innerHTML = ""
//先清空字符串
cunfang.forEach(function (v, i) {
$("ul").innerHTML += `<li>${v}</li>`
//再遍历cunfang组数向里面添加v值
})
}
function $(className) {
return document.querySelector(className)
}
</script>
</html>