Native JS realizes AutoComplete plug-in _javascript skill

Source: Internet
Author: User
Tags object object

In the actual project, can use other people to write good plug-ins to achieve related functions is best but, in order to save time costs, because some projects are more urgent, not enough time to let you write, even if you write, you also spend a lot of time debugging compatibility. But for the purpose of learning, you can use your leisure time, write yourself, see some native JS things, according to their own ideas do plug-ins, so that can improve the level.
Speaking of Autotemplete, many people have used, reference autotemplete.js, and then you can realize in the input box when the value of the prompt Drop-down options, similar to the Baidu search box that hint function, the following to say their own ideas.
Add input event for input box
The 1.input event compatibility code 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;
      }
    

Input events and other events, the low version of IE does not support input events, only with the PropertyChange event, the high version of IE and the standard browser support input events
2. Get data when input event is triggered
There are two forms of data here, one is directly set object array, one is AJAX request return data
This time we need an AJAX request function, where a GET request is written

Get:function (URL, paraobj, FN, timeout) {var xhr = null; try {////compatible firefox,chrom if (window).
          XMLHttpRequest) {xhr = new XMLHttpRequest (); //////compatible IE else if (window.activexobject) {xhr = new ActiveXObject ("Msxml2.xmlhttp"
          );
        The 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. Ajax request succeeded, and when there is data, create a Drop-down box and append options in the Drop-down box////create a Drop-down div
To create a drop-down box code:

Createshowdiv:function () {
 
      ///if Drop-down div already exists, delete
      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 Drop-down div
      var div = document.createelement (' div ');
      Div.id = this.config.showdivId;
      Set dropdown 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 Click event for dropdown 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 the main idea of a few steps, now look at how to encapsulate the code into an object, let it become plug-ins. This is where we use anonymous closures:

(function (Win) {
  var autocomplete= function () {this
    . Init.apply (this, arguments);
 
  Autocomplete.prototype = {
 
    ////Add related operation code
 
    Init: {},///initialization parameter
 
    Render: {},
 
    Createshowdiv: {},///create dropdown div
 
    appendchild: {},///appends the dropdown div with the item
 
    closediv: {},////closes the dropdown box
 
    //////tool objects, events, requests, and functions of the DOM node operation
 
    Util: {
 
      ADDEVT: {},///add event
 
      InsertAfter: {},///append element get after an element:
 
        {}////Ajax get request
 
    }
 
  win. autocomplete= function (paraobj) {
    new AutoComplete (paraobj). Render ();
  }
}) (window)


The code for the main body is added, so we'll show you 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: ',////display of the text's property name valuefiled: ', Gets the property name of value style: {},////The style setting URL for the Drop-down div displayed: ',//ajax requested URL paraname: ' Name ',//ajax
        Requested parameter Select:function () {},//event triggered when the option is selected, Showdivid: '//dropdown ' ID of the selected area};
      }}, 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) {////ajax request to fetch 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 sets the form of an object array else if (!self.config.url && self.config.data)
                  {Self.createshowdiv ();
                Self.appendchild (Self.config.data);
              } else {self.closediv ();
 The catch (e) {//todo Handle the exception             Alert (e);
        }
          }); ////Create a Drop-down div createshowdiv:function () {///If the Drop-down div already exists, delete the var parentnode = THIS.A Utoelement.parentnode | |
      This.autoElement.parentElement;
      var childnodes = parentnode.childnodes;
      var showdiv = document.getElementById (this.config.showdivId);
      if (showdiv) {parentnode.removechild (showdiv);
      }//create Drop-down div var div = document.createelement (' div ');
      Div.id = this.config.showdivId; Set dropdown div style var style = This.config.style | | {width: ' 200px ', Height: ' Auto ', backgroundcolor: ' #1c5683 ', cursor: ' pointer ', D
      Isplay: ' Block '};
      For (Var prop in style) {Div.style[prop] = Style[prop];
    } this.showdiv = div;
      ///the dropdown div to append the display item 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 Click event for dropdown 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);
    }); ////Closes 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;  },///append element insertafter:function (Ele, Targetele) {var parentnode = Targetele.parentnode after an element) ||
        Targetele.parentelement;
        if (Parentnode.lastchild = = Targetele) {parentnode.appendchild (ele);
        else {Parentnode.insertbefore (ele, targetele.nextsibling);
        },///get requests 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");
        The 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)

The following code is used

Page calls

Window.onload = function () {
  autocomplete ({
    id: ' txttest '),//control ID
    URL: '/home/test4 ',//Data
    Paraname: ' Name ',
    textfiled: ' name ',//////////////////////////////(//////////////////////
    //           URL: ',//ajax requested URL
    select:function (val, text) {
      alert (val + '---' + text);
    },//When option is selected Event,
    showdivid: ' Showdiv '//dropdown select Area ID};}
 

The background code is as follows, here I'm 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 the basic function implementation and call finished, from the beginning to the end of the process is more cumbersome, each method is step-by-step implementation, no reference to other libraries, to take into account the compatibility of each browser.

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.