In actual projects, it is best to use plug-ins written by others to implement related functions. However, in order to save time and cost, some projects are more urgent and do not have enough time to write on your own. Even if you write, you still have to spend a lot of time debugging compatibility. However, for the purpose of learning, you can use your spare time to write by yourself, read some native JS things, and make plugins according to your own ideas, so that you can improve your level.
Speaking of autotemplete, many people have used it. Refer to autotemplete.js, and then you can implement the prompt drop-down option when entering values in the input box. It is similar to the prompt function of Baidu search box. Let’s talk about your own ideas.
Add input event to the input box
1. The compatibility code of the input event is as follows:
AddEvt: 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; } }The input event is different from other events. The lower version of ie does not support input events, and can only use propertychange events. The higher version of ie and w3c standard browsers support input events.
2. Get data when the input event is triggered
There are two forms of data here, one is a direct set object array, and the other is ajax request to return data
At this time, we need an ajax request function, and a get request is written here
get: function(url, paraobj, fn, timeout) { var xhr = null; try { //// Compatible with firefox,chrom if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } ////// Compatible with IE else if (Window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.Xmlhttp"); } } catch (e) { //TODO handle the exception 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); } }; var parastr = ''; parastr += "?"; for (var prop in paraobj) { parastr += prop + "=" + paraobj[prop] + "&"; } xhr.open('get', parastr != "?" ? (url + parastr) : url, true); xhr.send(); }3. When the ajax request is successful and there is data, create a drop-down box and add options to the drop-down box //// Create a drop-down Div
Create a drop-down box code:
createShowDiv: function() { ///If the pull-down div already exists, delete the var parentNode = this.autoElement.parentNode || this.autoElement.parentElement; var childNodes = parentNode.childNodes; var showDiv = document.getElementById(this.config.showdivId); if (showDiv) { parentNode.removeChild(showDiv); } //Create the pull-down Div var div = document.createElement('div'); div.id = this.config.showdivId; //Set the drop-down div style var style = this.config.style || { width: '200px', height: 'auto', backgroundColor: '#1c5683', cursor: 'pointer', display: 'block' };<br> for (var prop in style) { div.style[prop] = style[prop]; } this.showdiv = div; }Append option code:
appendChild: function(data) { var self = this; var data = data; var fragment = document.createDocumentFragment(); for (var i = 0; i < data.length; i++) { var obj = data[i]; var child = document.createElement('div'); child.style.width = self.showdiv.style.width; child.style.border = '1px'; child.style.borderStyle = 'solid'; child.style.borderTopColor = 'white'; child.setAttribute('key', obj[self.config.valueFiled]); child.innerHTML = obj[self.config.textFiled]; fragment.appendChild(child); } self.showdiv.appendChild(fragment); self.util.insertAfter(self.showdiv, self.autoElement); //Add a click event for the drop-down box self.util.AddEvt(self.showdiv, 'click', function(e) { var evt = e || window.event; var target = evt.srcElement || evt.target; var key = target.getAttribute("key"); var val = target.innerHTML; self.autoElement.value = val; self.closeDiv(); self.config.select.call(self, key, val); }); }The above is a few main ideas. Now let’s take a look at how to encapsulate these codes into an object and make them a plug-in. At this time we use anonymous closure:
(function(win) { var autocomplete= function() { this.Init.apply(this, arguments); } autocomplete.prototype = { ////Add relevant operation code Init: {}, ///Initialization parameters Render: {}, createShowDiv: {}, ///Create drop-down div appendChild: {}, ///Add display item closeDiv: {}, ////Close the drop-down box/////// Tool objects, events, requests, and functions for dom node operations util: { AddEvt: {}, ///Add event insertAfter: {}, ///Add element after a certain element get: {} ///// Ajax get request} } win.Autocomplete= function(paraobj) { new autocomplete(paraobj).Render(); }})(window)The main code has been added, and we will display the specific implementation code:
(function(win) { var autocomplete = function () { this.Init.apply(this, arguments); } autocomplete.prototype = { Init: function() { var args = Array.prototype.slice.call(arguments); if (args && args.length > 0) { var config = args[0]; var getType = Object.prototype.toString; if (config && getType.call(config) == "[object Object]") { // this.config = config; this.config = config || { id: '', //Control id data: [], //Data textFiled: '', //Attribute name of the displayed text valueFiled: '', //Get the attribute name of the value style: {}, //Style setting of the displayed drop-down div url: '', //Ajax requested url paraName:'name', //Ajax requested parameter select: function() {}, //Event triggered when selecting options, showdivId: '' //Pull down to select the area id }; } } }, Render: function() { var self = this; if (self.config) { var autoElement = document.getElementById(self.config.id); this.autoElement = autoElement; if (autoElement) { self.util.AddEvt(this.autoElement, 'input', function() { try { if (autoElement.value) { //// How to request data if (self.config.url && !self.config.data) { var paraobj = {}; paraobj[self.config.paraName] = autoElement.value; self.util.get(self.config.url, paraobj, function (data) { self.createShowDiv(); self.appendChild(eval('(' + data + ')')); }, 10000); } /////Directly set the form of an object array else if (!self.config.url && self.config.data) { self.createShowDiv(); self.appendChild(self.config.data); } } else { self.closeDiv(); } } catch (e) { //TODO handle the exception alert(e); } }); } } }, //// Create a drop-down Div createShowDiv: function() { ///If the pull-down div already exists, delete the var parentNode = this.autoElement.parentNode || this.autoElement.parentElement; var childNodes = parentNode.childNodes; var showDiv = document.getElementById(this.config.showdivId); if (showDiv) { parentNode.removeChild(showDiv); } //Create the pull-down Div var div = document.createElement('div'); div.id = this.config.showdivId; //Set the pull-down div style var style = this.config.style || { width: '200px', height: 'auto', backgroundColor: '#1c5683', cursor: 'pointer', display: 'block' }; for (var prop in style) { div.style[prop] = style[prop]; } this.showdiv = div; }, ///Add the display item in the drop-down div appendChild: function(data) { var self = this; var data = data; var fragment = document.createDocumentFragment(); for (var i = 0; i < data.length; i++) { var obj = data[i]; var child = document.createElement('div'); child.style.width = self.showdiv.style.width; child.style.border = '1px'; child.style.borderStyle = 'solid'; child.style.borderTopColor = 'white'; child.setAttribute('key', obj[self.config.valueFiled]); child.innerHTML = obj[self.config.textFiled]; fragment.appendChild(child); } self.showdiv.appendChild(fragment); self.util.insertAfter(self.showdiv, self.autoElement); //Add a click event for the drop-down box self.util.AddEvt(self.showdiv, 'click', function(e) { var evt = e || window.event; var target = evt.srcElement || evt.target; var key = target.getAttribute("key"); var val = target.innerHTML; self.autoElement.value = val; self.closeDiv(); self.config.select.call(self, key, val); }); }, //// Close the drop-down box closeDiv: function () { if (this.showdiv) { this.showdiv.style.display = 'none'; } } , util: { ///Add event AddEvt: 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; } }, ///Add an element after an element insertAfter: function(ele, targetELe) { var parentnode = targetELe.parentNode || targetELe.parentElement; if (parentnode.lastChild == targetELe) { parentnode.appendChild(ele); } else { parentnode.insertBefore(ele, targetELe.nextSibling); } }, ///Get request get: function(url, paraobj, fn, timeout) { var xhr = null; try { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (Window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.Xmlhttp"); } } catch (e) { //TODO handle the exception 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); } }; var parastr = ''; parastr += "?"; for (var prop in paraobj) { parastr += prop + "=" + paraobj[prop] + "&"; } xhr.open('get', parastr != "?" ? (url + parastr) : url, true); xhr.send(); } } } win.AutoComplete = function (paraobj) { new autocomplete(paraobj).Render(); } })(window)Below is the code used
Page call
window.onload = function () { AutoComplete({ id: 'txtTest', //Control id url: '/Home/Test4', //Data paraName:'name', textFiled: 'name', //Attribute name of the displayed text: valueFiled: 'id', //Get the attribute name of the value// style: {}, //Style settings of the displayed drop-down div// url: '', //Ajax requested url select: function (val, text) { alert(val + '---' + text); }, //Events fired when selecting options, showdivId: 'showDIv' //Pull down to select the id of the region}); }); }The background code is as follows, here I am using mvc
public JsonResult Test4(string name){ var list=new List<Student>(); list.Add(new Student { id="1",name="aaaaa"}); list.Add(new Student { id = "2", name = "aacc" }); list.Add(new Student { id = "3", name = "aabb" }); list.Add(new Student { id = "4", name = "bbcc" }); if (!string.IsNullOrEmpty(name)) { list = list.Where(p => p.name.Contains(name)).ToList(); } return Json(list,JsonRequestBehavior.AllowGet);}Now that the basic function implementation and call are finished, the process from the beginning to the end is quite troublesome. Each method is implemented step by step, without referring to other libraries, and the compatibility of each browser must be taken into account.
The above is all about this article, I hope it will be helpful to everyone's learning.