Files
ClassContent/历届学生/front-end-team-10/项目练习/学生项目/韩孟雪/2023-2-24/百度搜索建议_js案例.html
2024-09-27 02:06:13 +08:00

89 lines
2.7 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>百度搜索建议_js案例</title>
</head>
<body>
<input type="text" name="" id="">
<button>搜索</button>
<ul>
</ul>
</body>
<!-- 实现搜索建议
给input绑定oninput事件,实时获取用户输入的文本
从本地的所有搜索建议的数组中,筛选出包含用户输入内容的搜索建议
把符合条件的展示再ul li 里面给用户看
给ul li 中所有的li都绑定点击事件,点击时获取 li的文本内容,并为输入框赋值
然后实现百度搜索
关键字加红 -->
<script>
var keywordList = [
'今天出太阳了', '太阳很好', '不喜欢js学习',
'js编程很简单', '喜欢很简单的html', '今天不想学习html,只想出去玩',
'今天不想学习css', '今晚出去飙车', '明天出去修车'
];
var newKeyList = [];
$("input").oninput = () => {
// console.dir($("input").value);
newKeyList = []
if ($("input").value.length > 0) {
keywordList.forEach((v, i) => {
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 添加标签
var liHtml = ""//清空上一次的记录
newKeyList.forEach(v => {
liHtml += `<li>${v}</li>`
})
// console.log(liHtml);
$("ul").innerHTML = liHtml
bindLiClick();
}
function bindLiClick() {
// console.log(v);
_("ul li").forEach(v => {//循环添加onclick事件
v.onclick = () => {
console.log(v);
$("input").value = v.innerText
SearchBaidu(v.innerText)
}
})
}
$("button").onclick = () =>{
SearchBaidu($("input").value)
}
// for(var i = 0;i<keywordList.length; i++){
// console.log(keywordList[i]);
// console.log(i);
// }
//封装获取元素
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>