本文实例为大家分享了js实现百度淘宝搜索功能的具体代码,供大家参考,具体内容如下
由于没有后台数据,用数组模拟一下后台返回的数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box{
width:214px;
/*height: 400px;*/
margin: 100px auto;
position: relative;
}
</style>
</head>
<body>
<div class="box">
<input type="text" id="txt">
<input type="button" id="btn" value="搜索">
</div>
<script src="common.js"></script>
<script>
//模拟后台的数据
var keyWords = [
"一马当先",
"一箭双雕",
"一丝不苟",
"一心二用",
"吃火锅",
"吃鸡肉",
"吃鸡腿",
"吃鸡蛋",
"哈1哈",
"嘻1嘻",
"呜1呜",
];
//给文本框注册键盘松开事件
$query("#txt").onkeyup = function () {
var txt = $query("#txt").value;
if ($query(".box div")) {
$query(".box").removeChild($query(".box div"));
}
if (txt.length == 0) {
if ($query(".box div")) {
$query(".box").removeChild($query(".box div"));
}
return;
}
var newArr = [];
for (var i = 0; i < keyWords.length; i++) {
if (keyWords[i].indexOf(txt) !=-1) {
newArr.push(keyWords[i]);
}
}
if (newArr.length > 0) {
var newBox = document.createElement("div");
newBox.style.border = "1px solid red";
newBox.style.width = "100%";
$query(".box").appendChild(newBox);
for (var j = 0; j < newArr.length; j++) {
var newP = document.createElement("p");
newP.style.width = "100%";
newP.innerText = newArr[j];
newP.onmouseover = function () {
this.style.backgroundColor = "yellow";
}
newP.onmouseout = function () {
this.style.backgroundColor = "";
}
newBox.appendChild(newP);
}
}
console.log(newArr);//打印匹配的数据
}
</script>
</body>
</html>
最后,附上效果图,确实丑了点?
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。