Web Learning note 13-Mobile End search box prompt feature __web

Source: Internet
Author: User

Recent projects have been updated in iterations, nothing new to do, so take out a search for a small module to share, the function is to input keywords can come out related word association bar, delete some words can be saved by the time of the association, from the appearance, the effect is just, here to share to everyone, you can see.
The effect chart is as follows, GitHub link in this Search_demo

Follow the old rules, write the process directly below the first step: Create a file

Create the appropriate html,js,css file and introduce jquery.
Step Two: Introduce files, set meta, write HTML, and style

Html:

<! DOCTYPE html>

Css:

*{margin:0;
padding:0;
    body{background-color: #f5f5f9; search_nav{width:100%;
    height:45px;
    position:fixed;
    top:0;
    left:0;
Background-color: #20232b;
    }. search_input{Float:left;
    width:75%;
    height:35px;
    margin-left:30px;
    margin-top:5px;
    font-size:15px;
    text-indent:30px;
    BORDER:1PX solid black;
    border-radius:40px;
Outline:none;
    } Input::-webkit-search-cancel-button {Display:none}. search_cancel{float:right;
    width:15%;
    height:100%;
    Color:white;
    Text-align:center;
line-height:45px;
    }. search_find{background: #fff;
    line-height:42px;
margin-top:45px;
    }. search_history{padding-left:10px;
    font-weight:700;
    FONT-SIZE:16PX}. search_find_title{Display:block;
    position:relative;
    padding-left:15px;
    padding-right:10px;
    font-size:14px;
    Color: #8a8a8a;
    width:100%;
  Box-sizing:border-box}. search_find_title:after{  Content: ';
    Position:absolute;
    top:0;
    left:15px;
    Box-sizing:border-box;
    width:92%;
    height:1px;
    Color: #ddd;
    border-bottom:1px solid #ddd; -webkit-transform-origin:0
    0; transform-origin:0
    0;
    -webkit-transform:scaley (. 4);
 Transform:scaley (. 4)}

Of course, this style of the pattern in their own actual projects need to adjust according to their own projects, do not need to write the same as I do, the important is the logical part. Step Three: Write JS logic

Under normal circumstances, when we enter the search page, most of the history of the search, that is, search records, we need first is to carry out the historical search rendering, I here historical search is to use localstorage for storage, we can carry out corresponding storage or acquisition according to need.

var history_search = [];//store historical search data

//Get historical search data, if not, null if
(Localstorage.getitem ("History_search")) {
    History_search = Json.parse (Localstorage.getitem ("History_search"))//Get historical search data
}else{history_search
    = [];
}

Next, on the premise of capturing the history, we're going to render the history to the page.

Render History
Function Setpage () {
    var product_list = ';
    Dynamically adding elements to the page
    if (history_search.length!= 0) {
        $ (". Search_history"). Show ();
        if (History_search.length >=) {for
            (var i = 0; i < i++) {
                product_list = ' <a class= ' search_find_title "> ' +history_search[i]+ ' </a>";
                $ (". Search_find_line"). Append (product_list);
            }
        else{for
            (var i = 0; i < history_search.length;i++) {
                product_list = ' <a class= ' search_find_title ' > ' + history_search[i]+ ' </a> ';
                $ (". Search_find_line"). Append (Product_list);}}
    else{
        $ (". Search_history"). Hide ();
    }
Setpage ();

What we need to be aware of here is that the general history of the record is not too much, General will show the first 10 recent search, my side in the rendering of the time to do the interception, in fact, in the deposit should be to make judgments, in excess of 10 or the number of rules when we only save 10 or the number of rules, Then there is no need to intercept it when rendering.

The next thing you need to do is when you enter the keyword, some request and cache the search for the prompt data

var Obj_arr = [];//request result
var timeout = 0;
var keyname = '//search keyword
var ajaxcache = {};//Define cache object (save requested data)

Here I first put the other two methods first to write, one is the way to render the page, one is to determine whether the string is empty method, the two methods in the next logical need to call.

Render Page Method
function Setlistpage (obj,no) {
    console.log (obj);
    Console.log (no);
    Ajaxcache = {};
    Obj_arr = obj;
    $ (". Search_find_line"). empty ();
    if (no = = 1) {
        $ (". Search_history"). Hide ();
    } else{
        $ (". Search_history"). Show ();

    var search_res = ';
    for (var i = 0; i < obj.length;i++) {
        search_res = ' <a class= ' search_find_title ' > ' +obj[i]+ ' </a> ';
        $ (". Search_find_line"). Append (Search_res);
    }

Determines whether the string is null
function IsNull (str) {
    if (str = "") return true;
    var Regu = "^[]+$";
    var re = new RegExp (regu);
    return Re.test (str);

This is the most important part of it.

When the button is released, the event $ ('. Searchproduct ') is triggered. KeyUp (function (evt) {//get to keyword KeyName = $ (this). Val ();//Determine if the keyword is an empty if (IsNull (ke Yname) = = False | |
        KeyName!= ') {//If the input string is not empty, a network request search is displayed.
        Cleartimeout (timeout); Timeout = settimeout (function () {if (!!)
                Ajaxcache[keyname]) {//Display an automatic prompt box to fill in the contents of the associated entry in the box Setlistpage (ajaxcache[keyname],1);
            Ajaxcache = {};

                }else{var senddata = {"KeyName": KeyName};
                    $.ajax ({type: POST), url:url,//our own interface is not open, we can use their own.
                        Data:JSON.stringify (SendData), DataType: ' JSON ', success:function (data) {
                        Console.log (data);
                                if (data) {if (data.data) {//Display an automatic prompt box, fill in the box with the contents of the associated entry Ajaxcache[keyname]=[];
                            ajaxcache[keyname]=data.data;//assigns a value to the cached object Setlistpage (data.data,1);
                        }}, Error:function (err) {
                    Console.log (ERR);
            }
                });
    }},200);
        }else{//If the input string is empty, the history search is displayed.
        Ajaxcache = {};
        if (History_search.length = = 0) {//If the array is empty, historical search does not show $ (". Search_history"). Hide ();
            }else{$ (". Search_history"). Show (); Setlistpage (history_search,2)}}//Mobile phone side of the lower right corner of the search button when the trigger event if (Evt.keycode =) {Localstorage.seti
        TEM (' search_keyname ', keyname);
        var count = 0; Determine if the keyword for the current search exists in the history search (var j = 0; J < history_search.length;j++) {if KeyName = = History_search [j])
            {count = 1;
 }else{count + 0;           }//If not, add the history search if (count = = 0) {history_search.unshift (keyname);
        //This lack of processing is a matter of historical search sequencing.
        Localstorage.setitem ("History_search", Json.stringify (History_search));
 Window.location.href= "";//jump to page such as search results page}

     This is basically done, there is no search results page, in the presence of prompt search, should be in <a class= "Search_find_title" ></a> Add click event to jump to the search results page and so on, this side can be handled according to their own needs.

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.