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

100 lines
2.6 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>
<style>
* {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<input type="text" placeholder="请输入关键字">
<button>搜索</button>
<ul>
</ul>
</body>
<script>
// 实现搜索建议
// 1 放置input,button,ul li
// 2 给input绑定 oninput 事件,实时获取用户输入的 东西
// 3 从本地的所有搜索建议的数组中,筛选出包含 用户 输入内容 的 搜索建议
// 4 把符合条件的 展示 在 ul li 里面给用户看
// 5 给 ul li 中所有 li 都绑定点击事件,点击时候获取 li 的文本内容,并为输入框重新赋值,
// 然后实现百度搜索。
// 关键字加红
var keyWordList = [
'今天出太阳了', '太阳很好', '不喜欢js学习',
'js编程很简单', '喜欢很简单的html', '今天不想学习html,只想出去玩',
'今天不想学习css', '今晚出去飙车', '明天出去修车'
];
var newKeyList = []
// for(var i = 0;i<keyWordList.length;i++) {
// console.log(keyWordList[i]);
// console.log(i);
// }
$("input").oninput = () => {
newKeyList = []
if ($("input").value.length > 0) {
keyWordList.forEach(v => {
if (v.includes($("input").value)) {
var text = v.replace($("input").value, `<span style="color:red;">${$("input").value}</span>`)
newKeyList.push(text)
}
})
console.log("符合条件的数据:", newKeyList);
renderUl()
} else {
$("ul").innerHTML = ""
}
}
function renderUl() {
$("ul").innerHTML = ""
newKeyList.forEach(v => {
$("ul").innerHTML += `<li>${v}</li>`
})
bindLiClick()
}
function bindLiClick() {
_("ul li").forEach(v => {
v.onclick = () => {
console.dir(v);
$("input").value = v.innerText
SearchBaidu(v.innerText)
}
})
}
$("button").onclick = () => SearchBaidu($("input").value)
function SearchBaidu(text) {
open(`https://www.baidu.com/s?wd=${text}`)
}
function $(className) {
return document.querySelector(className)
}
function _(className) {
return document.querySelectorAll(className)
}
</script>
</html>