<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
padding-top: 100px;
text-align: center;
}
#dv p{
margin: 0;
padding: 0;
cursor: pointer;
padding: 5px 0;
}
</style>
</head>
<body>
<input type="text" id="txt">
<button>百度一下</button>
<div id="box"></div>
<script src="common.js"></script>
<script>
//1.准备数据
var keyWords = ["吃火锅", "吃鱼", "吃卫龙", "吃火腿", "吃火鸡面", "吃火龙果", "喝烫水","喝水"];
//2.给文本框注册键盘抬起事件
my$('txt').onkeyup = function () {
//优化: 每次键盘抬起判断页面中有没有这个div
if(my$("dv")){
my$("box").removeChild(my$("dv"));
}
//console.log(this.value);
var text = this.value;//获取文本框的值
//存放能对应上的数据
var arr = [];
for(var i = 0 ; i < keyWords.length ; i++){
//判断值是不是当前数据中最开始出现的
if(keyWords[i].indexOf(text) == 0){
//console.log(text+"=============="+keyWords[i].indexOf(text));
arr.push(keyWords[i]);
}
}
console.log(arr);
//优化: 如果文本框是空的, 临时的数组也是空的, 不需要创建div
if(text.length == 0 || arr.length == 0){
//需要判断是否存在, 不然会报错
if (my$("dv")) {
my$("box").removeChild(my$("dv"));
}
return false;
}
//3.把对应的数据显示到页面
var box = document.createElement("div");
my$("box").appendChild(box);
box.id = "dv";
box.style.border = "1px solid green";
// box.style.height = "50px";
//遍历添加
for(var i = 0 ; i < arr.length; i++){
var pObj = document.createElement("p");
box.appendChild(pObj);
//设置内容
pObj.innerHTML = arr[i];
//鼠标进入
pObj.onmouseover = function () {
this.style.backgroundColor = "pink";
}
//鼠标移出
pObj.onmouseout = function () {
this.style.backgroundColor = "";
}
//鼠标点击
pObj.onclick = function () {
my$("txt").value = this.innerText;
my$("box").removeChild(my$("dv"));
}
}
}
</script>
</body>
</html>
来源:oschina
链接:https://my.oschina.net/u/4412725/blog/3514532