搜索框检索案例
代码展示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #box { width: 450px; margin: 200px auto; } #txt { width: 350px; } </style> </head> <body> <div id="box"> <input type="text" id="txt" value=""> <input type="button" id="btn" value="搜索"> </div> <script> function my$(id) { return document.getElementById(id); } var lists=["学习收藏","学习手册","权威指南","入门到精通","入门到入土","学无止境"]; my$("txt").onkeyup = function () { //每次键盘抬起事件触发时,先判断是否有div,有就删除一次 if(my$("dv")){ my$("box").removeChild(my$("dv")) } var tem = []; var t = this.value; for (var i=0;i<lists.length;i++){ if (lists[i].indexOf(t) == 0){ tem.push(lists[i]); /*将符合条件的放到临时数组里*/ } } //创建div,用放符合的词条 var dvObj = document.createElement("div"); my$("box").appendChild(dvObj); dvObj.id = "dv"; dvObj.style.width = "350px"; dvObj.style.border = "1px solid green"; //判断搜索框是否是空白或者临时数组是否有符合的词条,是则将创建的div删除 if (this.value == 0 || tem.length ==0){ if(my$("dv")){ my$("box").removeChild(my$("dv")); } return } //将符合检索条件的词条循环放入创建的div中 for (var j=0;j<tem.length;j++){ pObj = document.createElement("p"); my$("dv").appendChild(pObj); //标签添加文本的兼容代码 function setInnerText(element,text){ if (typeof (element.textContent) == "undefined") { element.innerText = text; }else{ element.textContent = text; } } setInnerText(pObj,tem[j]); pObj.style.margin = "0"; pObj.style.padding = "0"; pObj.style.cursor = "pointer"; pObj.style.marginTop = "5px"; pObj.style.marginLeft = "5px"; pObj.onmouseover = function () { this.style.backgroundColor = "yellow"; }; pObj.onmouseout = function () { this.style.backgroundColor = ""; } } } </script> </body> </html>