최근 드롭 다운 옵션이 너무 많으면 컨텐츠를 검색하기 위해 키워드를 입력하기를 희망하지만 프로젝트는 너무 서두르므로 Native JS와 함께 콘텐츠를 작성하기 때문에 할 시간이 없었기 때문에 플러그인은 Native JS를 사용하여 다음 아이디어를 작성합니다.
1 단계 : FNINIT 구현은 일부 필드를 초기화합니다
2 단계 : 검색 창에 DIV를로드하십시오
3 단계 : 검색 함수 구현, 원래 노드 삭제 및 새 노드를로드합니다.
4 단계 : 클릭하거나 입력 할 때 값을 설정합니다
암호:
autocomplete.js
/** * @summary autocomplete * @description 입력 상자는 드롭 다운 옵션을 자동으로 검색합니다 * @version 0.0.1 * @file autocomplete.js * @author cangowu * @contact [email protected] * @Copyright Copyright 2016 Cangowu. * 이것은 기본 J를 기반으로 검색을 자동으로 완료하는 드롭 다운 입력 상자입니다. * 마우스를 위아래로 누르고 마우스로 직접 클릭 할 수 있습니다. * 검색 옵션을 선택하고 일부 주요 장소에 주석이 있습니다. * 예제는 다음과 같습니다. * CSDN 블로그 : http://blog.csdn.net/wzgdjm/article/details/51122615 * github : https:/github */cangecetube */cangeal. {function autocomplete (! ``, 텍스트 파일 : // 표시된 텍스트의 속성 이름 : '', // 값 스타일의 속성 이름을 가져옵니다. {}, droplow DIVILED URL : '', // ajax rectime : // 옵션을 선택할 때 {}; Odefault.id. adata.data valuefiled. 전달 된 데이터는 데이터를 전달하지 않으면 데이터를 사용하여 데이터를 사용하여 데이터를 사용합니다 Stextfield는 this.StextFiled; 이 경우에 해당하는 DIV를 생성합니다 '절대'; 1px solid #a9a9a9 '; that.util.fnaddevent (that.dominput, 'keyup', function (event) {that.fnsearch (event);}), fnsearch : function (event) {// 키를 위아래로 내려 가면 검색을 수행 할 때 (keycode! = 13 && keycode! = 38 && this.fnshowdiv (); this.dominput.value = this.ssearchvalue; } this.dominput.value = this.domdiv.childnodes [this.index] .text; this.fnchangeclass (); } else if (event.keyCode == 38) {this.index-; if (this.index <= -1) {this.index = 길이 -1; } else if (this.index == -1) {this.obj.value = this.ssearchValue; } this.dominput.value = this.domdiv.childnodes [this.index] .text; this.fnchangeclass (); } else if (event.keyCode == 13) {this.fnloadSearchContent (); this.fnshowdiv (); //this.domdiv.style.display = this.domdiv.style.display === 'none'? '블록': '없음'; this.index = -1; } else {this.index = -1; }}}, fnloadsearchContent : function () {// 모든 자식 노드 삭제 while } // 검색 값을 설정 this.ssearchvalue = this.dominput.value; // 값이 비어 있으면 var strimsearchvalue = this.ssearchvalue.replace (/(^/s*) | (/s*$)/g, '')를 종료하려면 선택하십시오. if (strimsearchvalue == "") {this.domdiv.style.display = 'none'; 반품; } try {var reg = new regexp ( "(" + strimsearchvalue + ")", "i"); } catch (e) {return; } // 새 노드 검색 및 추가 var ndivindex = 0; for (var i = 0; i <this.adata.length; i ++) {if (reg.test [this.adata [i] [this.stextFiled])) {var domdiv = document.createElement ( "div"); //div.classname="auto_onmouseout "; domdiv.text = this.adata [i] [this.stextFiled]; domdiv.onclick = this.fnsetValue (this); domdiv.onmouseover = this.fnautoonmouseover (this, ndivindex); domdiv.innerhtml = this.adata [i] [this.stextFiled] .replace (reg, "<strong> $ 1 </strong>"); // 검색 된 문자는 this.domdiv.appendChild (domdiv); ndivindex ++; }}}, fnsetValue : function (that) {return function () {that.dominput.value = this.text; that.domdiv.style.display = 'none'; }}, fnautoonMouseOver : function (that, idx) {return function () {that.index = idx; that.fnchangeclass (); }}, fnchangeclass : function () {var that = this; var 길이 = that.domdiv.children.length; for (var j = 0; j <length; j ++) {if (j! = that.index) {that.domdiv.childnodes [j] .style.backgroundcolor = ''; that.domdiv.childnodes [j] .style.color = '#000'; } else {that.domdiv.childnodes [j] .style.backgroundcolor = 'blue'; that.domdiv.childnodes [j] .style.color = '#fff'; }}}, fnshowdiv : function () {if (this.domdiv.children.length! == 0) {this.domdiv.style.display = this.domdiv.style.display === 'none'? '블록': '없음'; }}, util : {// public interface method fninsertafter : function (ele, targetele) {var parentnode = targetele.parentNode || TargetEle.parentElement; if (parentnode.lastchild == targetEle) {parentnode.appendChild (ele); } else {parentnode.insertbefore (ele, targetele.nextsibling); }}, fnaddevent : function (ele, evt, fn) {if (document.addeventListener) {ele.addeventListener (evt, fn, false); } else if (docut } else {ele [ 'on' + (evt == "input"? "PropertyChange": evt)] = fn; }}, fnget : function (url, fn, timeout) {var xhr = null; try {if (wind } else if (wind }} catch (e) {// todo는 예외 xhr = new ActiveXobject ( 'microsoft.xmlhttp')를 처리합니다. } xhr.onreadyStateChange = function () {if (this.readyState == 4 && this.status == 200) {fn.call (this, this, this.responsetext); } else {settimeout (function () {xhr.abort ();}, timeout); }}; xhr.open ( 'get', url, true); xhr.send (); }}} window.autocomplete = function (옵션) {var aoption = array.prototype.slice.call (인수); for (var i = 0; i <aoption.length; i ++) {var autocomplete = new autocomplete (); autocomplete.fninit (aoption [i]); autocomplete.fnrender (); } } })(창문);
index.html
<! docType html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> title </title> </head> <body> <div> <입력 유형 = "text"id = "txttest"> </div> <br> <input type = "txttest1"> src = "autocomplete.js"> </script> <cript> wind "bbbwu bb"}, { "id": "2", "name": "bbbzbb"}], "bbbzbb"}], 'name', 'name', 'name', 'name', // 표시된 텍스트의 속성 이름 : 'id', // 값의 값의 이름을 선택하십시오 : {val, text) {val + '' + ' +' ' +' + ' +' + ''; } // 옵션을 선택할 때 트리거 된 이벤트}; var Option1 = {id : 'txtTest1', // 컨트롤 ID URL : 'data.json', // data paraname : 'name', 'name', 'name', 'name', // 표시된 텍스트의 속성 이름 : // 값의 값의 속성 이름을 선택 (val, text) {alert (alert (aler + ' + text); } // 옵션을 선택할 때 트리거 된 이벤트}; 자동 완성 (옵션, 옵션 1); } </script> </body> </html>Data.json
[{ "id": "1", "name": "aaaaa"}, { "id": "2", "name": "bbbbb"}, { "id": "3", "name": "cccccc"}]위의 내용은이 기사에 관한 모든 것입니다. 모든 사람들이 JavaScript 프로그래밍을 배우는 것이 도움이되기를 바랍니다.