Files
ClassContent/历届学生/刘合群/2019-07-19/输入提示.html
2024-09-27 02:06:13 +08:00

48 lines
1.4 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 name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js 仿照百度输入提示</title>
</head>
<body>
<input type="text" placeholder="亲输入关键词">
<ul class="listItem">
</ul>
<script>
var keyWord = document.querySelector("input");
var list = [ '今天很热', '天气不好','html编程学习','学习更多知识','今天学js' ]
var newList = []
keyWord.oninput = function () {
newList = []
// 为了避免用户删除搜索框文字后产生的导致indexOf返回0进而 newList 存储list数据
if (keyWord.value.length != 0) {
// 遍历 搜索候选建议数组
for(var i = 0; i < list.length; i++) {
// 匹配用户搜索的词在 搜索候选建议数组 中是否有
if (list[i].indexOf(keyWord.value) > -1) {
// 如果有把单词放到新数组
newList.push(list[i])
}
}
Render()
}
}
// 渲染 newList 数组的数据到 html页面上
function Render () {
document.querySelector(".listItem").innerHTML = ""
newList.forEach(function(val){
document.querySelector(".listItem").innerHTML += `<li>${val}</li>`
})
}
</script>
</body>
</html>