Baru-baru ini, ketika ada terlalu banyak opsi drop-down, saya berharap dapat memasukkan kata kunci untuk mencari konten, tetapi proyek itu terlalu terburu-buru sebelumnya, jadi saya tidak punya waktu untuk melakukannya karena saya berharap dapat menulis beberapa konten dengan JS asli, jadi plug-in menggunakan JS asli untuk menulis ide berikut berikut
Langkah 1: Implementasi FNINIT menginisialisasi beberapa bidang
Langkah 2: Muat div di kotak pencarian
Langkah 3: Menerapkan fungsi pencarian, hapus node asli dan muat node baru
Langkah 4: Tetapkan nilai saat mengklik atau masuk
Kode:
AutoComplete.js
/** * @summary AutoComplete * @Description Kotak input secara otomatis mengambil opsi drop-down * @Version 0.0.1 * @File AutoComplete.js * @Author cangowu * @contact [email protected] * @copyright Copyright 2016 CANGOWU 2016. * Ini adalah kotak input drop-down yang secara otomatis menyelesaikan pencarian berdasarkan JS asli. * 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 (! (Contohnya AutoComplete) {return new AutoComplete () ', TextFiled:' ', // Nama atribut dari teks yang ditampilkan Valuefiled:' ', // Dapatkan nama atribut dari gaya nilai: {}, // pengaturan gaya div yang ditampilkan: // Option yang diminta. odefault.id; ini. Ajax mendapatkan data. this.stextfiled; // menghasilkan div yang sesuai, hosting beberapa opsi berikutnya jika (itu 'Absolute'; that.util.fnaddevent (that.domInput, 'keyup', function (event) {that.fnsearch (event);});}, fnsearch: function (event) {// menilai apakah itu bukan key, event. this.fnloadSearchContent (); 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 = length - 1; } lain jika (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'? 'blok': 'tidak ada'; this.index = -1; } else {this.index = -1; }}}, fnloadSearchContent: function () {// hapus semua node anak sementara (this.domDiv.haschildnodes ()) {this.domDiv.removechild (this.domDiv.firstChild); } // Atur nilai pencarian this.ssearchValue = this.domInput.value; // Jika nilainya kosong, pilih untuk keluar var strimsearchValue = this.ssearchValue.replace (/(^/s*) | (/s*$)/g, ''); if (strimsearchValue == "") {this.domDiv.style.display = 'none'; kembali; } coba {var reg = regexp baru ("(" + strimsearchValue + ")", "i"); } catch (e) {return; } // Cari dan tambahkan simpul baru var nDivIndex = 0; untuk (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 (ini); domDiv.onmouseover = this.fnautoonmouseOver (ini, ndivindex); domDiv.innerHtml = this.adata [i] [this.stextfiled] .replace (reg, "<strong> $ 1 </strong>"); // karakter yang dicari menunjukkan this.domDiv.applchild (domDiv); ndivindex ++; }}}, fnsetValue: function (itu) {return function () {that.domInput.value = this.text; that.domdiv.style.display = 'none'; }}, fnautoonMouseOver: function (itu, idx) {return function () {that.index = idx; that.fnchangeClass (); }}, fnchangeClass: function () {var that = this; var length = that.domDiv.children.length; untuk (var j = 0; j <panjang; 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'? 'blok': 'tidak ada'; }}, util: {// Metode antarmuka publik 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 (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; coba {if (window.xmlHttpRequest) {xhr = new xmlHttpRequest (); } else if (window.activexObject) {xhr = new ActivexObject ("msxml2.xmlhttp"); }} catch (e) {// TODO menangani pengecualian 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, true); xhr.send (); }}} window.autocomplete = function (opsi) {var aoption = array.prototype.slice.call (argumen); untuk (var i = 0; i <aoption.length; i ++) {var autoComplete = new AutoComplete (); autocomplete.fninit (aoption [i]); autocomplete.fnrender (); }}}) (jendela);
index.html
<! Doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <iteme> title </iteme> </pead> <body> <dv> <input type = "text" id = "txttest"> </div> <br> <Div> <input type = "Text" ID = " src = "autoComplete.js"> </script> <script> window.onload = function () {var option = {id: 'txttest', // kontrol data id: [{"id": "1", "name": "aaaaa"}, {"id": "2", "nama": "BBB" {"ID": "2", "" BBB "{" ID ":" 2 "," "" " "bbbWu bb" }, { "id": "2", "name": "bbbzbb" }], paraName: 'name', textFiled: 'name', //The attribute name of the displayed text Filed: 'id', //Get the attribute name of the value of the value select: function (val, text) { alert(val + '' + text); } // acara dipicu saat memilih opsi}; var option1 = {id: 'txttest1', // control id url: 'data.json', // data paraname: 'name', textfiled: 'name', // nama atribut dari teks yang ditampilkan diajukan: 'id', // dapatkan nama atribut nilai dari nilai select: function (val, teks) {val + ' } // acara dipicu saat memilih opsi}; AutoComplete (opsi, opsi1); } </script> </body> </html>data.json
[{"id": "1", "name": "aaaaa"}, {"id": "2", "name": "bbbbb"}, {"id": "3", "name": "cccccc"}]Di atas adalah semua tentang artikel ini, saya harap akan sangat membantu bagi semua orang untuk mempelajari pemrograman JavaScript.