js实现百度淘宝搜索功能

时间:2021-05-26

本文实例为大家分享了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; 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>

最后,附上效果图,确实丑了点?

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章