Javascriptsuggest results automatically complete implementation code sharing _ javascript skills

Source: Internet
Author: User
Like Baidu and google, when we enter something into the search box, a list of top or suitable candidate words is displayed, which is called suggest. This article will teach you how to design it step by step. First, the Framework used is of course my Framework mass Framework. Of course, you can use other frameworks, such as jQuery. There is nothing complicated. As long as you understand the principle, you can make it all at once. Presumably, you will also encounter a search box job in your work in the future.

Because I do not have a backend, I use an object as a local database. What I want to do now is actually far more advanced than suggest, something similar to IDE syntax prompts. The current finished product has been put on github.

Let's get started. The first is the structure layer. If FF is installed, you can view the source code on the Baidu homepage. When several letters are entered, the HTML is generated dynamically. However, a DIV is placed at the bottom of the search bar, and a table is placed in it to dynamically store candidate words. In addition, if the candidate words are not part of the user input, that is to say, the parts automatically supplemented by JS will be put into a B label for rough display. However, I think the use of table is too quantitative, and I switched to the ul list. In order to allow IE6 to also support the color-changing effect, I also set a label in it. I also added an attribute for it (tag a) to store the words that have been added to the meta. It seems like this:

The Code is as follows:










  • User input
    Automatic prompt




  • User input
    Automatic prompt







Taking a look at the structure, there are actually two parts: p # search_wrapper is visible, p # suggest_wrapper is "invisible" (as long as there is no li element in it, it does not occupy space and cannot be displayed ). The input search box has an attribute autocomplete, which is used to disable the prompt function that comes with the browser. For data-value, this naming method is recommended by html5. it is used to define the data to be cached. data-* will be placed in an object named dataset in the cutting-edge browser. For example:

The Code is as follows:


Data-drink = "coffee"
Data-meal-time = "12:00"> 12: 00



You can access it as follows:

The Code is as follows:


Var el = document. getElementById ('situ Zheng mei ');
Alert (el. dataset. drink );
Alert (el. dataset. mealTime );


Of course, you can also directly obtain the innerText or textContext of the a tag without setting attributes.
Note: complete vocabulary = user input + automatic prompt. Therefore, you should not add so many things to tag a to prevent leading to retrieval failures due to space or space!
The style section is followed, but it is not detailed. Simple:

The Code is as follows:


# Search_wrapper {
Height: 50px;
}
# Search {
Width: 300px;
}
# Suggest_wrapper {
Position: relative;
}
# Suggest_list {
Position: absolute;
Z-index: 100;
List-style: none;
Margin: 0;
Padding: 0;
Background: # fffafa;
Border: 1px solid # ccc;
Border-bottom: 0 none;
}
# Suggest_list li {
Display: block;
Height: 20px;
Width: 304px;
Color: #000;
Border-bottom: 1px solid # ccc;
Line-height: 20px;
Text-decoration: none;
}
# Suggest_list li a: hover,. glow_suggest {
Background: # ffff80;
}


Okay, it's important. Because I have no background, I want to use a local object as a local database. This object is of course a JS object. The objects we traverse are generally obj. aaa. bbb. ccc. in this way, we can continue to traverse through the for in loop every time a dot is reached. Therefore, we listen to the input of text content, and retrieve the content of the input box as soon as it changes, and then compare it in the for in loop. If it is an attribute starting with this input value, it will be taken out and put into an array. It will take up to ten attributes, and then splice the contents of these arrays into the li element format described above, it is attached to the ul element. In this example, we should also note that if we enter the DoT number at the beginning, we will take the ten properties of the window object. In the future, we will switch this object when we encounter the DoT number.
Now, start to write the code. Because my framework is used, you can go here. There is README on the project homepage to teach you how to install a micro. Net Server and view the documentation. In the beginning, you should regard it as jQuery that has added the module loading function. API 90% is similar. We need to use its event module and attribute module. It loads the relevant dependencies and then adds the ready parameter, which will be executed after domReady. Select the input box and bind an input event to it. This is an event supported by a standard browser. My framework under IE is compatible, use jQuery to simulate the propertychange event.

The Code is as follows:


// By SITU zhengmei
$. Require ("ready, event, attr", function (){
Var search = $ ("# search"), hash = window, prefix = "", fixIE = NaN;
Search. addClass ("search_target ");
Search. input (function () {// listen for input
Var
Input = this. value, // Original value
Val = input. slice (prefix. length), // compare Value
Output = []; // used to place the output content
If (fixIE = input ){
Return // enable IE to change the value in the input box through the program will also trigger the propertychange event, so that we cannot perform the up/down Operation
}
For (var prop in hash ){
If (prop. indexOf (val) === 0) {// obtain the API that starts with the input value
If (output. push ('

  • Prop + '">' + input +""+ (Prefix + prop). slice (input. length) +"
  • ") = 10 ){
    Break;
    }
    }
    }
    // If you encounter a forward vertex or cancel the backward Vertex
    If (val. charAt (val. length-1) = "." | (input &&! Val )){
    Var arr = input. split ("."); hash = window;
    For (var j = 0; j <arr. length; j ++ ){
    Var el = arr [j];
    If (el & hash [el]) {
    Hash = hash [el]; // reset the object to traverse the API
    }
    }
    Prefix = input = "."? "": Input;
    For (prop in hash ){
    If (output. push ('
  • Prop + '">' + input +""+ (Prefix + prop). slice (prefix. length) +"
  • ") = 10 ){
    Break;
    }
    }
    }
    $ ("# Suggest_list" ).html (output. join (""));
    If (! Input) {// reset all
    Hash = window;
    FixIE = prefix = output = [];
    }
    });
    });


    When the prompt list is displayed, we listen for the top-down and bottom-up effects. That is, when you click the orientation key of the keyboard, it will display the highlighted entries and fill them in the search box. In this case, you need to bind the keyup event and check its keyCode. The standard browser manages it as which. You can view my blog Summary of javascript Keyboard Events. The implementation principle is very simple. It defines a peripheral variable, which is used to store the highlighted position (index value). Then, when you use flip, the variable is reduced by one. When you use flip, the variable is added, then retrieve all the tags in the prompt list, locate a tag with the index value, highlight it, and remove the previously highlighted a tag.

    The Code is as follows:


    // By SITU zhengmei
    $. Require ("ready, event, attr", function (){
    Var search = $ ("# search"), hash = window, prefix = "";
    Search. input (function () {// listen for input
    //.....
    });
    Var glowIndex =-1;
    $ (Document). keyup (function (e) {// listen for up/down
    If (/search_target/I. test (e.tar get. className) {// proxy only for specific elements to improve performance
    Var upOrdown = 0
    If (e. which = 38 | e. which = 104) {// up 8
    UpOrdown --;
    } Else if (e. which = 40 | e. which = 98) {// down 2
    UpOrdown ++;
    }
    If (upOrdown ){
    Var list = $ ("# suggest_list ");
    // Transfer highlighted Columns
    List. eq (glowIndex). removeClass ("glow_suggest ");
    GlowIndex + = upOrdown;
    Var el = list. eq (glowIndex). addClass ("glow_suggest ");
    FixIE = el. attr ("data-value ")
    Search. val (fixIE)
    If (glowIndex === list. length-1 ){
    GlowIndex =-1;
    }
    }
    }
    });
    });


    Finally, press enter to submit. I wrote another keyup event. Of course you can try to merge two keyups into one (Listening to the window). I write this purely for the purpose of teaching.

    The Code is as follows:


    // By SITU zhengmei
    $. Require ("ready, event, attr", function (){
    Var search = $ ("# search"), hash = window, prefix = "";
    Search. input (function () {// listen for input
    //.....
    });
    Var glowIndex =-1;
    $ (Window). keyup (function (e) {// listen for up/down
    //.....
    });
    Search. keyup (function (e) {// listener submits
    Var input = this. value;
    If (input & (e. which = 13 | e. which = 108) {// if you press ENTER
    Alert (input) // in the actual project, it should jump to the page and go to the search result page!
    }
    });
    });


    At this point, the suggest effect is complete. If you go to my framework, enable the server and open the document homepage to see this effect. In actual projects, suggest is actually simpler. When the text in the input box changes, AJAX requests an array in the background and then concatenates it into the format of the li element.
    Related Article

    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.