http://www.javashuo.com/article/p-ssjrmiha-ba.htmlhtml
點擊查看連接!!!app
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>模糊查詢</title> <script src="static/js/jQuery%20v1.9.1.js"></script> <style> *{ list-style: none; padding:0; margin:0; } div{ text-align: center; padding-top:20px; } ul{ padding-top:20px; width:30%; margin:0 50% 0 35%; } li{ padding:3px; border:1px solid silver; box-shadow: 1px 1px; } </style> </head> <body> <div> <input type="text" id="txt"> <button type="button" id="btn">search</button> <ul id="list"> </ul> </div> <script> var oTxt = document.getElementById('txt'); var oBtn = document.getElementById('btn'); var oList = document.getElementById('list'); var fruits = ["桃子","蘋果","梨子","香蕉","香瓜","葡萄","檸檬","橘子","草莓","草莓子","草擬嗎","s","ssr"]; //點擊事件 oBtn.addEventListener('click', function(){ var keyWord = oTxt.value; // var fruitList = searchByIndexOf(keyWord,fruits); console.log(fruitList); var fruitList = searchByRegExp(keyWord, fruits); renderFruits(fruitList); }, false); //回車查詢 oTxt.addEventListener('keydown', function(e){ if(e.keyCode == 13){ var keyWord = oTxt.value; // var fruitList = searchByIndexOf(keyWord,fruits); var fruitList = searchByRegExp(keyWord, fruits); renderFruits(fruitList); } }, false); var cpLock = false; $('#txt').on('compositionstart', function () { cpLock = true; console.log("不搜索") }); $('#txt').on('compositionend', function () { cpLock = false; console.log("漢字搜索"); var keyWord = oTxt.value; // var fruitList = searchByIndexOf(keyWord,fruits); var fruitList = searchByRegExp(keyWord, fruits); renderFruits(fruitList); }); $('#txt').on('input', function () { if (!cpLock) { console.log("字母搜索") var keyWord = oTxt.value; // var fruitList = searchByIndexOf(keyWord,fruits); var fruitList = searchByRegExp(keyWord, fruits); renderFruits(fruitList); } }); function renderFruits(list){ if(!(list instanceof Array)){ return ; } oList.innerHTML = ''; var len = list.length; var item = null; for(var i=0;i<len;i++){ item = document.createElement('li'); item.innerHTML = list[i]; oList.appendChild(item); } } //模糊匹配的時候若是不區分大小寫,可使用toLowerCase()或者toUpperCase()轉換以後去匹配。 //模糊查詢1:利用字符串的indexOf方法 function searchByIndexOf(keyWord, list){ if(!(list instanceof Array)){ return ; } var len = list.length; var arr = []; for(var i=0;i<len;i++){ //若是字符串中不包含目標字符會返回-1 if(list[i].indexOf(keyWord)>=0){ arr.push(list[i]); } } return arr; } //正則匹配 function searchByRegExp(keyWord, list){ if(!(list instanceof Array)){ return ; } var len = list.length; var arr = []; var reg = new RegExp(keyWord); for(var i=0;i<len;i++){ //若是字符串中不包含目標字符會返回-1 if(list[i].match(reg)){ arr.push(list[i]); } } return arr; } renderFruits(fruits); </script> </body> </html>