This article describes in detail the information about the intelligent prompt control intelliseach. js Based on jquery. If you are interested, refer to it.
I. Requirements
We often encounter the need for intra-site search. To improve the user experience, we hope to provide instant smart prompts like Baidu. For example, if you want to search for Li XX in a company's personnel management system and enter "Li", the system will naturally prompt some employees surnamed Li for convenience. To put it bluntly, the system will prompt relevant results when the user inputs them. Or, when the user clicks the search box, it will recommend some content, for example, 360 and Baidu will prompt you about the major news or content with a large search volume today.
Jquery already has such a plug-in called autocomplete, but I think it is not easy to use. There are also many introductions about autocomplete. If you are interested, you can try it.
You can see the title. Here we only share a plug-in. We will not discuss the algorithms and processes related to background search. That is to say, the control is responsible for rendering the results when the background returns data in a specific format. OK. Let's take a look:
Style has nothing to do with the control. Only one input text is required.
Ii. parameter description
The control is transmitted in json format. There are many parameters, most of which have default values (For details, refer to the source code), and some may not be commonly used. Keep the default values. As follows:
Url:Request address. For example, Handler. ashx, the address for retrieving data in the background
Property:Attributes of the json object to be displayed. If we directly return the form ["tom", "tom cat", "tom2"], you do not need to set this attribute. However, sometimes we return [{"Name ": "tom", "ID": "001" },{ "Name": "tom cat", "ID": "002" },{ "Name ": "tom2", "ID": "003"}]. If the Name is displayed, set this attribute to "Name. As for the ID of the item to be clicked, click the event.
ItemNumber:The number of items displayed.
IsEmptyRequest:Whether to initiate a request in the blank space when focusing. As mentioned above, if you click the search box (NO content at this time) and want to recommend some content, set this attribute to true, a request will be initiated.
DefaultValue:Default value. Usually there are prompts such as "Enter keywords.
Width:The width of the drop-down list.
Aligner:The element to be aligned.
MaxHeight:Maximum height. If this height is set, a scroll bar will appear when it exceeds.
Ajax:{
Timeout: timeout
Cache: whether to cache
},
Event:{
SetData: triggered before sending a request. Used to set parameters
ItemClick: triggered by a click item
EnterKeydown: Press enter to trigger
BeforeRender: triggered before all items are displayed
EndRender: triggered after all items are rendered
ItemBeforeRender: triggered before the item is displayed
ItemAfterRender: triggered after the item is rendered
BeforeSend: triggered before sending a request. The user sets parameters in the Request Header, which is equivalent to the beforeSend of jquery ajax.
}
The methods in event are triggered when appropriate. Note that all methods receive a parameter, which is an object with four attributes, in some cases, this attribute is null. Includes the following attributes:
Jthis:Input jQuery object.
JItem:JQuery object.
Data:The returned json string. If you need to process the returned json in the foreground, you can obtain it through the data attribute. After processing, you need to return the json string.
Event:Event object, such as the event object when you press enter.
Iii. Example
Example:
$ ("# Search "). intellisearch ({url: "Handler. ashx ", property:" Name ", itemNumber: 5, isEmptyRequest: false, defaultValue:" Enter keywords... ", width: $ (" # search "). width () + 2, maxHeight:-1, event: {itemClick: function (obj) {alert (obj. item. ID) ;}, enterKeydown: function (obj) {if (obj. item) {alert ("current item");} else {alert ("no current item ");}}}});
Iv. Summary
If you still have your own logic to be processed, you can also perform chained calling. You can write $ ("# search") in this way "). intellisearch ({parameter ...}). focus (function () {your processing ...});
Share this plug-in to help friends who need it, mainly for learning. Because it is v1.0, there may be some bugs. If you find it, you can tell me that I will fix it in time.
Source code
Js Code
/* Search smart prompt v1.0 date: 2015.09.08 */; (function (w, $) {$. fn. intellisearch = function (options) {var jthis = this; var _ dftOpts = {url: "", // request address or array property :"", // The itemNumber: 5 attribute of the json object to be displayed, // The number of items displayed isEmptyRequest: false, // whether to initiate the request defaultValue: "", // default width: 0, // list width aligner: jthis, // elements to be aligned maxHeight:-1, // max height ajax: {timeout: 3000, // timeout cache: true // cache?}, event: {/* parameter description: parameter: {jthis: "jq input", jItem: "Jq item", data: "json result", event: "event"} */setData: null, // set the itemClick parameter to null, // click the item to trigger enterKeydown: null, // press enter to trigger beforeRender: null, // endRender: null is triggered before all items are rendered, // trigger itemBeforeRender: null after all items are rendered, // trigger itemAfterRender: null before the item is displayed, // trigger beforeSend: null after the item is displayed // trigger before the request is sent}; $. extend (_ dftOpts, options); if (! _ DftOpts. url) {throw Error ("url cannot be blank! ");} Var jResult; var _ value =" "; var _ ajax = _ dftOpts. ajax; var _ event = _ dftOpts. event; var _ cache = []; var _ focusCount = 0; // prevents the focus from being triggered multiple times (sogou)/* on window */window. intellObj = window. intellObj | {};/* for global event */window. intellidocumentclick = window. intellidocumentclick | function (e) {if (! Window. intellObj. jthis) {return;} if(e.tar get! = Window. intellObj. jthis [0]) {setIntellObj (null) ;}} window. intellidocumentkeydown = window. intellidocumentkeydown | 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. intellidocumentclick, keydown: window. intellidocumentkeydown }). bind ({click: window. intellidocumentclick, keydown: window. intellidocumentkeydown}); 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? _ DftOpts. width: _ dftOpts. aligner. width (); jResult = $ ("
", {" Class ":" intelliresult "}); 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 = $ (t His); 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, B EforeSend: function (xhr) {if (_ event. beforeSend) {_ event. beforeSend (xhr) ;}, success: function (data) {remove (); showData (data) ;}, error: null});} function showData (data) {data = $. trim (data )? $. 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 )? Data: [data]; var length = list. length; length = length> _ dftOpts. itemNumber? _ DftOpts. itemNumber: list. length; if (length <= 0) {return;} initIntell (); _ cache. length = 0; hasProp = list [0] [_ dftOpts. property]; for (var I = 0; I
", {" Class ":" intelliresult_item "}); jA =$ (" ", {" title ": text }). appendTo (jItem); jSpan = $ (""). 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) {$ ("
", {" Text ": otherTexts [0]}). insertBefore (jSpan); $ ("", {" Text ": otherTexts [1]}). insertAfter (jSpan);} else {if (index = 0) {$ ("", {" Text ": otherTexts [0]}). insertAfter (jSpan);} else {$ ("", {" 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 );
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;}
The above is all the content of this article, hoping to help you learn.