Home > Web Front-end > JS Tutorial > body text

Implementing intelligent prompt control based on jquery intellSeach.js_jquery

WBOY
Release: 2016-05-16 15:10:31
Original
1263 people have browsed it

1. Demand

We often encounter the need for [site search]. In order to improve the user experience, we hope to achieve real-time intelligent prompts like Baidu's. For example: in a company's personnel management system, if you want to search for Li XX, just enter "Li", and the system will naturally prompt some employees named Li, which is convenient for users. To put it bluntly, the system will prompt relevant results while the user is typing; or, when the user clicks on the search box, it will recommend some content. For example, 360 and Baidu will prompt today's main news or content with large search volume.

jquery already has a plug-in like this, called autocomplete, but I don’t think it’s easy to use. There are also many introductions to autocomplete. Friends who are interested can try it.

As you can tell from the title, this is just a plug-in and will not discuss the relevant algorithms and processes of background search. In other words, the background returns data in a specific format, and the control is responsible for rendering the results. ok, let’s take a look at the renderings first:

 

The style has nothing to do with the control, only an input text is needed.

2. Parameter description

The control uses json format as the transmission format. There are many parameters, most of which have default values ​​(see the source code for details). Some may not be commonly used, so just keep the default values. As follows:

  url: Request address. For example: Handler.ashx, the address for obtaining data in the background

  property: The property of the json object to be displayed. If we directly return the form ["tom","tom cat","tom2"], then this attribute does not need to be set; but sometimes we will return [{"Name":"tom","ID":" 001"},{"Name":"tom cat","ID":"002"},{"Name":"tom2","ID":"003"}] In this form, Name is displayed. Then set this property to "Name". As for the ID of the clicked item we want to get when clicking, we can use the click event.

  itemNumber: The number of items displayed.

  isEmptyRequest: Whether to initiate a request when blank. As mentioned before, if you want to recommend some content when you click on the search box (there is no content at this time), set this attribute to true, and a request will be initiated.

 defaultValue: Default value. Usually it will be a prompt like: "Please enter the keyword...".

  width: Drop-down list width.

  aligner: The element to be aligned.

 maxHeight: Maximum height. If this height is set, scroll bars will appear when it is exceeded.                                                                          

 

ajax:{ Timeout: Timeout
cache: Whether to cache
},  

 

event:{    ​​​​​ setData: Triggered before sending the request. Used to set parameters
itemClick: Triggered by clicking on item
             enterKeydown: Triggered by pressing the enter key
           beforeRender: Triggered before all items are rendered
endRender: triggered after all items are rendered
itemBeforeRender: Triggered before item is rendered
itemAfterRender: Triggered after the item is rendered
             beforeSend: Triggered before sending the request. The user sets request header parameters, etc., which is equivalent to jquery ajax's beforeSend.
}

The methods in event will be triggered at the appropriate time. It should be noted that all methods receive a parameter, which is an object with 4 attributes. In some cases, if there is no such attribute, it will be empty. Includes the following attributes:

  jthis: jQuery object of input.

  jItem: The jQuery object of the item.

data: The json string returned. If the returned json needs to be processed in the foreground, it can be obtained through the data attribute. After the processing is completed, the json string needs to be returned.

 event: Event object, such as the event object when enter is pressed.

3. Example

Usage example:

$("#search").intellSearch({
  url:"Handler.ashx",
  property:"Name",
  itemNumber:5,
  isEmptyRequest:false,
  defaultValue:"请输入关键字...",    
  width:$("#search").width() + 2,
  maxHeight:-1,
  event:{
    itemClick:function(obj){
      alert(obj.item.ID);
    },
    enterKeydown:function(obj){
      if(obj.item){
        alert("有当前项");
      }else{
        alert("没有当前项");
      }
    }
  }  
});
Copy after login

4. Summary 

If you still have your own logic to process and chain calls are supported, you can write $("#search").intellSearch({parameters...}).focus(function(){your processing ...});

Sharing this plug-in hopes to help friends in need. It is mainly used for learning. Since it is v1.0, there may still be some bugs. Friends who find them can also tell me and I will correct them in time. ​

Source code attached

js code

/*搜索智能提示 v1.0
 date:2015.09.08 
*/
;(function(w,$){
  $.fn.intellSearch = function(options){
    var jthis = this;
    var _dftOpts = {
      url:"",//请求地址或数组          
      property:"",//要显示的json对象的属性
      itemNumber:5,//显示的条数
      isEmptyRequest:false,//focus空白是否发起请求
      defaultValue:"",//默认值
      width:0,//列表宽度
      aligner:jthis,//要对齐的元素
      maxHeight:-1,//最大高度          
      ajax:{
        timeout:3000,//超时时间
        cache:true//是否缓存
      },
      event:{
        /*参数说明:parameter:{jthis:"jq input",jItem:"jq item",data:"json result",event:"event"}*/
        setData:null,//设置参数
        itemClick:null,//点击项触发
        enterKeydown:null,//按下enter键触发
        beforeRender:null,//所有项呈现前触发
        endRender:null,//所有项呈现后触发
        itemBeforeRender:null,//项呈现前触发
        itemAfterRender:null,//项呈现后触发
        beforeSend:null//发送请求前触发
      }
    };
    $.extend(_dftOpts,options);
    if(!_dftOpts.url){
      throw Error("url不能为空!");
    }
    var jResult;        
    var _value = "";    
    var _ajax = _dftOpts.ajax;
    var _event = _dftOpts.event;
    var _cache = [];
    var _focusCount = 0;//防止focus触发多次(sogou)
     
    /*on window*/
    window.intellObj = window.intellObj || {}; /*for global event*/
    window.intellDocumentClick = window.intellDocumentClick || function(e){
      if(!window.intellObj.jthis){
        return;
      }
      if(e.target !== window.intellObj.jthis[0]){
        setIntellObj(null);
      }
    }
    window.intellDocumentKeydown = window.intellDocumentKeydown || function(e){
      var jthis = window.intellObj.jthis;
      if(!jthis){
        return;
      }
      var code = e.keyCode;
      var value = window.intellObj.value;      
      var jResult,jCurItem,keyword;
      if(code === 13 || code === 38 || code === 40){
        jResult = window.intellObj.jResult;
        jItems = jResult.find("li");
        jCurItem = jResult.find("li.cur");
        if(code === 13){
          if(jCurItem.length > 0){
            jCurItem.click();
          }else{
            setIntellObj(null);           
            if(_event.enterKeydown){
              _event.enterKeydown({"jthis":jthis,"event":e});
            }
          }
          jthis.blur();
        }else if(jItems.length > 0){
          if(code === 38){
            if(jCurItem.length <= 0){
              jCurItem = jItems.last();
              jCurItem.addClass("cur");
              keyword = jCurItem.text();
            }else{
              var index = jCurItem.index();
              jCurItem.removeClass("cur");
              if(index <= 0){
                keyword = value;              
              }else{
                jCurItem = jItems.eq(index-1);
                jCurItem.addClass("cur");
                keyword = jCurItem.text();
              }
            }
            jthis.val(keyword);
          }else{
            if(jCurItem.length <= 0){
              jCurItem = jItems.first();
              jCurItem.addClass("cur");
              keyword = jCurItem.text();
            }else{
              var index = jCurItem.index();
              jCurItem.removeClass("cur");
              if(index + 1 >= jItems.length){
                keyword = value;
              }else{
                jCurItem = jItems.eq(index+1);
                jCurItem.addClass("cur");
                keyword = jCurItem.text();
              }
            }
            jthis.val(keyword);
          }
        }
      }
    }
    /*event handler*/
    $.fn.unintell = function(){
      remove();
    }
    $(document).unbind({click:window.intellDocumentClick,keydown:window.intellDocumentKeydown})
          .bind({click:window.intellDocumentClick,keydown:window.intellDocumentKeydown});
    jthis.focus(function(){
      _focusCount++;
      if(_focusCount > 1){
        return;
      }
      if(window.intellObj.jthis && jthis !== window.intellObj.jthis){
        setIntellObj(null);
      }
      var keyword = attrValue();
      if(keyword === _dftOpts.defaultValue){
        keyword = "";
        attrValue(keyword);
      }
      if(keyword || _dftOpts.isEmptyRequest){
        sendRequest();
      }
    })
    jthis.blur(function(){      
      _focusCount = 0;
      if(!attrValue()){
        attrValue(_dftOpts.defaultValue);
      }      
    })
    jthis.keyup(function(e){
      if(e.keyCode === 38 || e.keyCode === 40){
        return;
      }
      var keyword = attrValue();
      if(!keyword){
        remove();
        window.intellObj.value = _value = "";
        return;
      }
      if(keyword !== _value){
        window.intellObj.value = _value = keyword;
        sendRequest();
      }
    });
     
    return initBox();
     
    /*function*/
    function initBox(){
      attrValue(_dftOpts.defaultValue);
      return jthis;
    }    
    function initIntell(){      
      generate();
      register();
      setIntellObj({jthis:jthis,jResult:jResult});
    }
    function generate(){
      var offset = _dftOpts.aligner.offset();
      var width = _dftOpts.width &#63; _dftOpts.width : _dftOpts.aligner.width();
      jResult = $("<ul>",{"class":"intellResult"});
      jResult.width(width).css({"position":"absolute","left":offset.left,"top":offset.top + jthis.outerHeight()});
      $("body").append(jResult);
      if(_dftOpts.maxHeight > 0){
        jResult.height(_dftOpts.maxHeight).css("overflowY","scroll");
      }
    }
    function remove(){
      if(jResult){
        jResult.remove();
        jResult = null;
      }
    }
    function register(){
      jResult.on("click","li",function(){
        var jItem = $(this);
        var index = jItem.index();
        var keyword = jItem.text();
        attrValue(keyword);        
        _value = keyword;        
        if(_event.itemClick){
          _event.itemClick({"jthis":jthis,"jItem":jItem,"item":_cache[index]});
        }
      }).on("mouseenter","li",function(){
        $(this).siblings("li").removeClass("cur").end().addClass("cur");
      }).on("mouseleave","li",function(){
        $(this).removeClass("cur");
      });
    }
    function setIntellObj(obj){
      if(!obj){
        if(window.intellObj.jResult){
          window.intellObj.jResult.remove();
        }
        window.intellObj.jthis = null;
        window.intellObj.jResult = null;
      }else{
        window.intellObj.jthis = obj.jthis;
        window.intellObj.jResult = obj.jResult;
      }
    }
    function sendRequest(){
      var data;
      if(_event.setData){        
        data = _event.setData({"jthis":jthis});
      }
      $.ajax({
        url:_dftOpts.url,
        data:data,
        cache:_ajax.cache,
        timeout:_ajax.timeout,
        beforeSend:function(xhr){
          if(_event.beforeSend){
            _event.beforeSend(xhr);
          }
        },
        success:function(data){
          remove();
          showData(data);
        },
        error:null
      });
    }
    function showData(data){
      data = $.trim(data) &#63; $.parseJSON(data) : data;
      if(_event.beforeRender){
        var rs = _event.beforeRender({"jthis":jthis,"data":data});
        if(rs === false){
          return;
        }
        if(rs !== undefined){
          data = rs;
        }
      }
      if(!data){
        return;
      }
      var jItem,jA,jSpan,hasProp,item,text,otherTexts,isRender,index;
      var list = $.isArray(data) &#63; data : [data];
      var length = list.length;
      length = length > _dftOpts.itemNumber &#63; _dftOpts.itemNumber : list.length;
      if(length <= 0){
        return;
      }
      initIntell();
      _cache.length = 0;
      hasProp = list[0][_dftOpts.property];
      for(var i=0;i<length;i++){
        item = list[i];
        if(item === null || item === undefined){
          continue;
        }
        text = hasProp &#63; item[_dftOpts.property] : item;
        text = $.trim(text.toString());
        if(text === ""){
          continue;
        }
        jItem = $("<li>",{"class":"intellResult_item"});
        jA = $("<a>",{"title":text}).appendTo(jItem);
        jSpan = $("<span>").appendTo(jA);
        index = text.toLowerCase().indexOf(_value.toLowerCase());
        otherTexts = splitText(text,_value,index);
        if(otherTexts){
          jSpan.text(text.substr(index,_value.length));
          if(otherTexts.length > 1){
            $("<b>",{"text":otherTexts[0]}).insertBefore(jSpan);
            $("<b>",{"text":otherTexts[1]}).insertAfter(jSpan);
          }else{
            if(index === 0){
              $("<b>",{"text":otherTexts[0]}).insertAfter(jSpan);
            }else{
              $("<b>",{"text":otherTexts[0]}).insertBefore(jSpan);
            }
          }
        }else{
          jSpan.text(text);
        }
        isRender = true;
        if(_event.itemBeforeRender){
          isRender = _event.itemBeforeRender({"jthis":jthis,"jItem":jItem,"item":item});
        }
        if(isRender !== false){
          jResult.append(jItem);
          if(_event.itemAfterRender){
            _event.itemAfterRender({"jthis":jthis,"jItem":jItem,"item":item});
          }
        }
        _cache.push(item);
      }
      if(_event.endRender){
        _event.endRender({"jthis":jthis});
      }
      jResult.show();
    }
    function attrValue(value){
      if(!value && value != ""){
        return $.trim(jthis.val());
      }
      jthis.val(value);
    }
    function splitText(text,value,index){
      var tlength = text.length;
      var vlength = value.length;
      if(index === -1){
        return null;
      }
      if(index === 0){
        if(index + vlength >= tlength){
          return null;
        }
        return [text.substr(index + vlength)];
      }
      if(index + vlength >= tlength){
        return [text.substr(0,index)];
      }
      return [text.substr(0,index),text.substr(index + vlength)];
    }
  }
})(window,jQuery);
Copy after login

Style

.intellResult{margin:0;padding:0;background:#fff;border:1px solid #b6b6b6;clear:both;z-index:999;display:none;}
.intellResult li{margin:0;padding:0;padding:5px 15px;height:20px;line-height:20px;overflow:hidden;text-overflow:ellipsis;cursor:pointer;white-space:nowrap;}
.intellResult li.cur{background:#E5E0E0;}
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!