Recientemente, cuando hay demasiadas opciones desplegables, espero ingresar palabras clave para buscar contenido, pero el proyecto era demasiado apresurado antes, por lo que no tuve tiempo de hacerlo porque espero escribir algo de contenido con JS nativo, por lo que el complemento usa JS nativo para escribir la siguiente idea.
Paso 1: la implementación de FNINIT inicializa algunos campos
Paso 2: Cargue el div en el cuadro de búsqueda
Paso 3: Implemente la función de búsqueda, elimine el nodo original y cargue el nuevo nodo
Paso 4: Establezca el valor al hacer clic o ingresar
Código:
autocomplete.js
/** * @Summary AutoComplete * @Description El cuadro de entrada recupera automáticamente la opción desplegable * @Version 0.0.1 * @file Autocomplete.js * @Author CANGOWU * @Contact [email protected] * @Copyright Copyright 2016 CANGOWU. * Este es un cuadro de entrada desplegable que completa automáticamente la búsqueda en función de JS nativo. * Puede presionar las teclas hacia arriba y hacia abajo del mouse y hacer clic directamente con el mouse * Seleccione la opción de búsqueda, y hay comentarios en algunos lugares de clave * * Los ejemplos son: * Blog CSDN: http://blog.csdn.net/wzgdjm/article/details/51122615 * github: https://github.com/cangowu/aut * * * * * () {function autocomplete () {if (! (esta instancia de autocomplete)) {return new Autocomplete (); paraname: '', textfiled: '', // Nombre de atributo del valor de texto mostrado: '', // Obtener el nombre de atributo del estilo de valor: {}, // Configuración de estilo de la URL mostrada Div: '', // Ajax Solicitud ODEFAULT.ID; = _Option.Style || De lo contrario, use datos para obtener los datos if (this.surl! == '' && this.adata.length === 0) {var que = this.util.fnget (this.surl, function (data) {console.log (eval (data)); que.Adata = eval (data);}, 10); this.adata.sort (function (a, b) {return a [Stextfield]> B [Stextfield];}); Div, alojamiento de algunas opciones posteriores if (que.sdivid) = '1px Solid #A9A9A9'; 'KeyUp', Function (Event) {that.fnsearch (evento); } else {// monitorear eventos de teclado después de la longitud de búsqueda = this.domdiv.children.length; } this.dominput.Value = this.domDiv.childNodes [this.index] .Text; this.fnchangeclass (); } else if (event.keycode == 38) {this.index--; if (this.index <= -1) {this.index = longitud - 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 === 'Ninguno'? 'Bloque': 'Ninguno'; this.index = -1; } else {this.index = -1; }}}, fnloadSearchContent: function () {// Eliminar todos los nodos infantiles mientras (this.domDiv.haschildNodes ()) {this.domDiv.removechild (this.domdiv.firstchild); } // Establezca el valor de búsqueda this.ssearchValue = this.dominput.value; // Si el valor está vacío, seleccione para salir de var strImSearchValue = this.searchValue.replace (/(^/s*) | (/s*$)/g, ''); if (strimSearchValue == "") {this.domdiv.style.display = 'none'; devolver; } try {var reg = new Regexp ("(" + StrimSearchValue + ")", "i"); } catch (e) {return; } // buscar y agregar nuevo nodo 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.fautoonMouseOver (this, ndivindex); domdiv.innerhtml = this.adata [i] [this.stextfiled] .replace (reg, "<strong> $ 1 </strong>"); // Los caracteres buscados muestran esto.domdiv.appendChild (domdiv); ndivindex ++; }}}, fnsetValue: function (that) {return function () {that.domInput.Value = this.Text; que.domdiv.style.display = 'ninguno'; }}, fNaUtoonMouseOver: function (that, idx) {return function () {that.Index = idx; que.fnchangeclass (); }}, fnchangeclass: function () {var that = this; Var longitud = that.domdiv.children.length; for (var j = 0; j <longitud; j ++) {if (j! = that.index) {that.domDiv.childNodes [j] .style.backgroundcolor = ''; que.domdiv.childnodes [j] .style.color = '#000'; } else {that.domdiv.childnodes [j] .style.backgroundcolor = 'blue'; que.domdiv.childnodes [j] .style.color = '#fff'; }}}, fnshowdiv: function () {if (this.domdiv.children.length! == 0) {this.domdiv.style.display = this.domdiv.style.display === 'Ninguno'? 'Bloque': 'Ninguno'; }}, util: {// método de interfaz pública 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, falso); } else if (document.attachevent) {ele.attachevent ('on' + (evt == "input"? "PropertyChange": evt), fn); } else {ele ['on' + (evt == "input"? "PropertyChange": evt)] = fn; }}, fnget: function (url, fn, timeOut) {var xhr = null; Pruebe {if (window.xmlhttprequest) {xhr = new xmlhttprequest (); } else if (window.activexObject) {xhr = new ActiveXObject ("msxml2.xmlhttp"); }} catch (e) {// toDo manejar la excepción xhr = new ActiveXObject ('Microsoft.xmlhttp'); } xhr.OnreadyStateChange = function () {if (this.readyState == 4 && this.status == 200) {fn.call (this, this.ResponSetext); } else {setTimeout (function () {xhr.abort ();}, timeout); }}; xhr.open ('get', url, verdadero); xhr.send (); }}} window.autocomplete = function (opción) {var aOption = array.prototype.slice.call (argumentos); for (var i = 0; i <aoption.length; i ++) {var autocomplete = new AutoComplete (); autocomplete.fninit (aoption [i]); autocomplete.fnrender (); } } })(ventana);
index.html
; src="autoComplete.js"></script> <script> window.onload = function () { var option = { id: 'txtTest', //Control id data: [{ "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbbb" }, { "id": "2", "name": "bbbwu bb"}, {"id": "2", "nombre": "bbbzbb"}], paraname: 'name', textfiled: 'name', // el nombre de atributo del texto mostrado: 'id', // Obtener el nombre de atributo del valor del valor seleccionar: function (val, text) {alerta + ' + text); } // Evento activado al seleccionar una opción}; var option1 = {id: 'txtTest1', // Url de ID de control: 'data.json', // data paraname: 'name', textFiled: 'name', // atributo nombre del texto mostrado archivado: 'id', // Obtener el nombre de atributo del valor del valor seleccionar: function (val, texto) {alerta (val + '' + texto); } // Evento activado al seleccionar una opción}; Autocomplete (opción, opción1); } </script> </body> </html>data.json
[{"id": "1", "nombre": "aaaaa"}, {"id": "2", "nombre": "bbbbb"}, {"id": "3", "nombre": "ccccccc"}]Lo anterior se trata de este artículo, espero que sea útil para todos aprender la programación de JavaScript.