Recentemente, quando há muitas opções suspensas, espero inserir palavras-chave para procurar conteúdo, mas o projeto estava muito apressado antes, então não tive tempo de fazê-lo, porque espero escrever algum conteúdo com o JS nativo, então o plug-in usa js nativos para escrever a seguinte ideia
Etapa 1: A implementação do FNINIT inicializa alguns campos
Etapa 2: carregue a div na caixa de pesquisa
Etapa 3: implemente a função de pesquisa, exclua o nó original e carregue o novo nó
Etapa 4: Defina o valor ao clicar ou entrar
Código:
AutoComplete.js
/** * @Summary AutoComplete * @Description A caixa de entrada recupera automaticamente a opção suspensa * @Version 0.0.1 * @File AutoComplete.js * @author cangowu * @contact [email protected] * @copyright copyright 2016 Cangowu. * Esta é uma caixa de entrada suspensa que conclui automaticamente a pesquisa com base no JS nativo. * You can press the mouse up and down keys and click directly with the mouse* Select the search option, and there are comments in some key places* * Examples are: * CSDN blog: http://blog.csdn.net/wzgdjm/article/details/51122615 * Github: https://github.com/cangowu/autoComplete * */ (function () {function AutoComplete () {if (! '', Textfiled: '', // Nome do atributo do texto exibido Valuefiled: '', // Obtenha o nome do atributo do estilo de valor: {}, // Configuração de estilo da divisão Div exibida: '' ', // ajax solicitou URL: odefault.id; OSTYLE DE _OPTION DE Em, ajax obtém os dados. ASSINTE. // gera uma div, hospedando algumas opções subsequentes se (que. Domdiv.style.border = '1px sólido #a9a9a9'; that.util.fnadDevent (that.dominput, 'keyup', function (event) {that.fnsearch (event);}); thisshowdiv (); this.domInput.value = this.SearchValue; } this.dominput.value = this.domdiv.childnodes [this.index] .text; this.fnchanGeclass (); } else if (event.KeyCode == 38) {this.index--; if (this.index <= -1) {this.index = length - 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 === 'nenhum'? 'Block': 'Nenhum'; this.index = -1; } else {this.index = -1; }}}, fnloadSearchContent: function () {// Exclua todos os nós da criança while (this.domdiv.haschildnodes ()) {this.domdiv.removechild (this.domdiv.firstchild); } // Defina o valor de pesquisa this.SSearchValue = this.dominput.value; // Se o valor estiver vazio, selecione para sair var strimSearchValue = this.SearchValue.replace (/(^/s*) | (/s*$)/g, ''); if (strimsearchValue == "") {this.domdiv.style.display = 'nenhum'; retornar; } tente {var reg = new regexp ("(" + strimsearchValue + ")", "i"); } catch (e) {return; } // Pesquise e adicione novo nó 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>"); // Os caracteres pesquisados mostram isso.domdiv.appendchild (domdiv); ndivindex ++; }}}, fnSetValue: function (that) {return function () {that.dominput.value = this.text; that.domdiv.style.display = 'nenhum'; }}, fnaUtoonMouseOverover: function (que, idx) {return function () {that.index = idx; that.fnchanGeclass (); }}, fnchanGeclass: function () {var que = this; var comprimento = that.domdiv.children.length; for (var j = 0; j <comprimento; 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'; }}}, fnsShowdiv: function () {if (this.domdiv.children.length! == 0) {this.domdiv.style.display = this.domdiv.style.display === 'nenhum'? 'Block': 'Nenhum'; }}, util: {// Método da interface pública fninsertafter: function (ele, targetele) {var parablernode = 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 (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; tente {if (window.xmlHttPrequest) {xhr = new XmlHttPrequest (); } else if (window.activexObject) {xhr = new ActivexObject ("msxml2.xmlhttp"); }} catch (e) {// TODO lide a exceção 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 ();}, tempo limite); }}; xhr.open ('get', url, true); xhr.send (); }}} window.autocomplete = function (option) {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 (); } } })(janela);
index.html
<! Doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title> title </title> </ad Head> <body> <div> <input type = "text" id = "txtTest"> </div> <br> <div> <input = typet = "idiota =" = "=" TXTTest "> <br> <br> <br> <styp = typet =" "Id =" = "=" txtTest "> <br> <br> <br> <stpi) 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", "name": "bbbzbb"}], paraname: 'name', textfiled: 'name', // o nome do atributo do texto exibido (text): 'Id', // obtenha o nome do valor do valor do valor: Função: Val, text) (text) {',' } // evento acionado ao selecionar uma opção}; var option1 = {id: 'txtTest1', // Control Id url: 'data.json', // paraname de dados: 'nome', textfiled: 'nome', // nome do atributo do texto exibido arquivado: 'id', // obtenha o nome do atributo do valor do valor selecionar: função (val, text) {alert (valert (valer + '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '' '', } // evento acionado ao selecionar uma opção}; AutoComplete (opção, opção1); } </script> </body> </html>data.json
[{"id": "1", "nome": "aaaaa"}, {"id": "2", "nome": "bbbbb"}, {"id": "3", "nome": "cccccc"}]O exposto acima é tudo sobre este artigo, espero que seja útil para todos aprenderem a programação de JavaScript.