Files
ClassContent/历届学生/韩想/每日课程/2020-08-09/百度搜索建议.html
2024-09-27 02:06:13 +08:00

77 lines
2.0 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">
<title>百度搜索建议</title>
<style>
body,
ul,
li {
margin: 0;
padding: 0;
list-style: none;
}
</style>
</head>
<body>
<input type="text" placeholder="输入关键词">
<ul>
</ul>
</body>
<script>
// => 箭头函数function简写
// var name = fn() => {
// }
// var name = () => {
// }
var keyWordList = [
'今天', '今天天气不好', '天气是雨天', 'html', 'html学习', '不喜欢html',
'编程学习', '学习代码', '喜欢编程',
];
var newList = []
var input = document.querySelector("input");
var ul = document.querySelector("ul");
input.oninput = function () {
newList = []
if (input.value.length != 0) {
keyWordList.forEach(function (val, index) {
if (val.indexOf(input.value) > -1) {
// 获取 用户输入关键字在原字符串中的下标
let stringIndex = val.indexOf(input.value);
// 使用 substring 方法,提取 原字符串中 的 符合用户输入的字符
// let activeString = `<span style="color:red">${val.substring(stringIndex, stringIndex + input.value.length)}</span>`;
let activeString = `<span style="color:red">${input.value}</span>`;
// 替换原字符串中的关键词为带span的关键字
let newVal = val.replace(input.value, activeString)
newList.push(newVal)
}
});
ul.innerHTML = ""
newList.forEach(function (val, index) {
ul.innerHTML += `<li>${val}</li>`
})
console.log(newList);
} else {
ul.innerHTML = ""
}
}
</script>
</html>