JS——下拉搜索列表(模糊搜索匹配)

来源:转载

<script type="text/javascript">var datas = [{name:"总部管理支持部门",code:"0000-0001"},{name:"董事会秘书局",code:"0000-0001-0002"},{name:"总裁办公室",code:"0000-0001-0003"},{name:"规划发展部",code:"0000-0001-0004"},{name:"人力资源部",code:"0000-0001-0005"},{name:"财务部",code:"0000-0001-0006"}];//定义数据/*** 搜索下拉列表**/$('#testInput').bind('input propertychange',function() {var items = inputChange();//搜索数据并获取搜索结果if(items != undefined){_initItems(items);} });//1:搜索数据var inputChange = function() { var inputValue = $('#testInput').val();if(inputValue != "" && inputValue.indexOf("000") == -1){var matcher = new RegExp(inputValue, "i");return $.grep(datas,function(value) {return matcher.test(value.name);});}else if(inputValue != "" && inputValue.indexOf("000") != -1){var matcher = new RegExp(inputValue, "i");return $.grep(datas,function(value) {return matcher.test(value.code);});} }; var maxFontNumber = 0;//最大字数var suggestContainer = $('<div></div>'); //创建一个子<div>suggestContainer.attr('id', "testInput-suggest"); suggestContainer.attr('tabindex', '0'); suggestContainer.hide();//2:初始化搜索到的数据进行显示var _initItems = function(items) {$('#ruleOrgCode').val(""); suggestContainer.empty(); for (var i = 0; i < items.length; i++) {if(items[i].name.length > maxFontNumber){maxFontNumber = items[i].name.length;}var suggestItem = $('<div></div>'); //创建一个子<div> suggestItem.attr('code', items[i].code); suggestItem.append(items[i].name); suggestItem.css({'padding':'3px',//item间距 'white-space':'nowrap', 'cursor': 'pointer', 'background-color': 'RGB(199,237,204)',//默认背景颜色 'color': '#000000'//默认字体颜色 }); suggestItem.bind("mouseover", function() { $(this).css({ 'background-color': '#C9302C',//选中背景颜色 'color': '#ffffff'//选中字体颜色 }); }); suggestItem.bind("mouseout", function() { $(this).css({ 'background-color': 'RGB(199,237,204)',//默认背景颜色 'color': '#000000'//默认字体颜色 }); }); suggestItem.bind("click", showClickTextFunction);//选中后处理数据 //suggestItem.bind("click", itemSelectFunction); suggestItem.appendTo(suggestContainer); suggestContainer.appendTo(document.body); } suggestContainer.removeAttr("style");suggestContainer.css({ 'border': '1px solid #ccc', 'max-height': '200px', 'top': $('#testInput').offset().top + $('#testInput').outerHeight(), 'left': $('#testInput').offset().left, 'width': 12*maxFontNumber + 2 * 3 + 30, 'position': 'absolute', 'font-size': '12px' ,//默认字体大小 'font-family':'Arial', 'z-index': 99999, 'background-color': '#FFFFFF', 'overflow-y': 'auto', 'overflow-x': 'hidden', 'white-space':'nowrap' }); maxFontNumber = 0;suggestContainer.show(); };//3.选中后处理数据var showClickTextFunction = function() {//alert(this.innerText + "---" + this.getAttribute("code")); $('#testInput').val(this.innerText); $('#ruleOrgCode').val(this.getAttribute("code")); suggestContainer.hide(); };</script>



<body> <div><input type="text" id="testInput" /><input type="hide" id="ruleOrgCode" /></div> </body>


分享给朋友:
您可能感兴趣的文章:
随机阅读: