<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
li{
list-style: none;
padding-left: 5px;
margin-top: 5px;
}
#box {
width: 450px;
margin: 200px auto;
}
#txt {
width: 350px;
}
#ul {
width: 350px;
border: 1px solid red;
display: none;
}
#ul.show {
display: block;
}
</style>
</head>
<body>
<div id="box">
<input type="text" id="txt" value="">
<input type="button" value="搜索" id="btn">
<ul id="ul">
</ul>
</div>
<script>
// 定义新数组
var keyWords =
[{"word": "javascript:", "resrc": "ori", "source": ""}, {
"word": "javascript手册",
"resrc": "ori",
"source": ""
}, {"word": "javascript下载", "resrc": "ori", "source": ""}, {
"word": "javascript基础教程",
"resrc": "ori",
"source": ""
}, {"word": "javascript入门教程", "resrc": "ori", "source": ""}, {
"word": "javascript:void 0",
"resrc": "ori",
"source": ""
}, {"word": "javascript:closedialog", "resrc": "ori", "source": ""}, {
"word": "javascript是什么",
"resrc": "ori",
"source": ""
}, {"word": "javascript教程", "resrc": "ori", "source": ""}, {
"word": "javascript官网下载",
"resrc": "ori",
"source": ""
}];
//获取文本框注册键盘抬起事件
$("txt").addEventListener("keyup", function () {
//按下之前先显示ul
$("ul").className += " " + "show";
// 每次按下之前清空ul里面的所有节点
$("ul").innerHTML = "";
//新建空数组准备放置筛选出的字符串
var tmp = [];
for (var i = 0; i < keyWords.length; i++) {
//此处使用toUppenCase()转换是为了让搜索不区分大小写
if (keyWords[i].word.toUpperCase().indexOf(this.value.toUpperCase()) == 0 && this.value.length != 0) {
tmp.push(keyWords[i]);
}
}
//输出数组,查看是否异常
console.log(tmp);
// 判断是否输入空字符或者删掉所有东西
if (this.value.length == 0 || tmp.length == 0) {
$("ul").className = "";
}
// 循环创建li并且插入到ul中
for (var j = 0; j < tmp.length; j++) {
var li = document.createElement("li");
setInnerText(li, tmp[j].word);
$("ul").appendChild(li)
}
}, false)
function $(id) {
return document.getElementById(id);
}
function setInnerText(ele, txt) {
return ele.textContent ? ele.textContent = txt : ele.innerText = txt;
}
</script>
</body>
</html>