Compared with similar plug-ins, it features three features.
1. cache query results (fast secondary query)
2. Non-keyup listening (solving the problem that keyxxx events cannot be triggered in some systems/situations)
3. Simple parameters (nice looking ?)
The plug-in performance is still good. My E6500, 2 GB memory, a total of 4469 calls occurred in 30 seconds, taking 94.65 milliseconds; Baidu's is 2432 calls, 80.24 milliseconds.
Calling nearly doubled is a problem in jQuery, but I haven't figured out the specific reason. If the brother knows anything, please don't hesitate to give me some advice.
Call Method
Copy codeThe Code is as follows:
JQuery ("# kw"). suggest ({
Url: siteConfig. suggestionUrl,
Params :{
Kw: function () {return jQuery ("# kw"). val ()},
N: 10
}
});
Parameter url: baseUrl, for example, http://www.target.com/search.php
Parameter params: the Suffix List of the url. In this example, the combined url is: http://www.target.com/search.php? Kw = xxx & n = 10 & callback =? (Callback is added by default)
Parameter delay: the input interval, mainly to reduce the load. The larger the value, the lower the load, and the slower the query speed.
Parameter cache: Indicates whether to use the cache. The default value is true. For example, when "test" is searched, the program caches the corresponding query results and reads the results directly from the cache when the test is searched for the second time.
Parameter formId: required, form id
Callback: whether to use jsonp to handle cross-origin issues.
Core code:
Suggest. js
Copy codeThe Code is as follows:
(Function ($ ){
$. Tools = $. tools | {version: '1. 0 '};
$. Tools. suggest = {};
$. Tools. suggest. defaults = {
Url: null,
Params: null,
Delay: 100,
Cache: true,
FormId: '# search_form ',
Focus: null,
Callback: true
}
$. Tools. suggest. borderKey = {
UP: 38,
DOWN: 40,
TAB: 9,
ESC: 27,
ENTER: 13
}
$. Fn. suggest = function (options, fn ){
Var options, key = $. tools. suggest. borderKey;
If ($. isFunction (options )){
Fn = options;
Options = $. extend ({}, $. tools. suggest. defaults, key );
} Else {
Options = $. extend ({}, $. tools. suggest. defaults, key, options );
}
Return this. each (function (){
Var
Self = $ (this ),
Url = options. url,
Params = options. params,
SearchUrl = null,
Searchtimer = 0,
Delay = options. delay,
Cache = options. cache,
Callback = options. callback,
Formobj = $ (options. formId ),
Focus = options. focus,
Rebox = $ ('<ul/>'). attr ("id", "suggest "),
HtmlLi = null,
Litop = null,
Lileft = null,
Liwth = null,
Tip = false,
Val = null,
Rlen = null,
UP = options. UP,
DOWN = options. DOWN,
TAB = options. TAB,
ESC = options. ESC,
ENTER = options. ENTER,
Index =-1,
ChoseKey = null,
Backval = null,
Hidden = false,
Locksuggest = false
// Init
If (focus ){
Self. focus ();
Searchtimer = setInterval (getKey, delay );
}
Self. bind ("focus", function (){
Searchtimer = setInterval (getKey, delay );
// Initialize the value of backval When Triggering the focus
Backval = (backval = $. trim (self. val () = ''? Null: backval;
})
. Bind ("blur", function (){
ClearInterval (searchtimer );
Searchtimer = 0;
HideResult ();
})
. Bind ("keydown", function (e ){
// No switch is used for less than 10 items
If (e. keyCode = UP ){
ClearInterval (searchtimer );
Searchtimer = 0;
If(+('{suggest'}.css ('display') = 'None '){
ReSet ();
Return false;
}
Index --;
If (index <0 ){
Index = Math. abs (rlen)-1;
}
ChangeSelect (index );
E. preventDefault ();
Return false;
} Else if (e. keyCode = DOWN ){
ClearInterval (searchtimer );
Searchtimer = 0;
If(+('{suggest'}.css ('display') = 'None '){
ReSet ();
Return false;
}
Index ++;
If (index> = rlen ){
Index = 0;
}
ChangeSelect (index );
E. preventDefault ();
Return false;
} Else if (e. keyCode = TAB ){
ClearInterval (searchtimer );
Searchtimer = 0;
HideResult ();
} Else if (e. keyCode = ESC ){
ClearInterval (searchtimer );
Searchtimer = 0;
HideResult ();
Return false;
} Else if (e. keyCode = ENTER ){
ClearInterval (searchtimer );
Searchtimer = 0;
} Else if (searchtimer = 0 ){
Searchtimer = setInterval (getKey, delay );
}
});
// Obtain keywords
Function getKey (){
Val = $. trim (self. val ());
// Keywords are not empty and repeated
If (!! Val & val! = Backval ){
Backval = val;
// Set the cache to false If no result is cached.
If (cache &&!! $. Tools. suggest [val]) {
Index =-1;
Rlen = $. tools. suggest [val] [1];
AppendSuggest ($. tools. suggest [val] [0]);
} Else {
Searchurl = url + '? '+ $. Param (params );
GetResult (searchurl, function (htmltemp, htmllen ){
Index =-1;
Rlen = htmllen;
AppendSuggest (htmltemp );
});
}
}
// The keyword is empty.
If (!!! Val &&! Hidden ){
HideResult ();
}
}
// Obtain the prompt data
Function getResult (searchurl, fn ){
If (callback) {searchurl = searchurl + '& callback =? ';}
$. GetJSON (searchurl, function (data ){
Var htmltemp = '',
Htmllen = 0,
InputWord = self. val ()
$. Each (data. list, function (I, n ){
If (n. word! = InputWord ){
Htmltemp + = '<li>' + n. word + '</li> ';
Htmllen ++;
}
});
If (cache &&!!! $. Tools. suggest [val]) {$. tools. suggest [val] = [htmltemp, htmllen];}
Fn. call (document, htmltemp, htmllen)
});
}
// Insert prompt data
Function appendSuggest (result ){
Locksuggest = hidden = false;
If (!! Result ){
If (! Tip ){
Litop = self. offset (). top + self. outerHeight ()-1;
Lileft = self. offset (). left;
Liwth = self. outerWidth ()-2;
Rebox.css ({'position': 'absolute ', 'top': litop, 'left': lileft, 'width': liwth+#.html (result ). appendTo ('body '). show ();
Tip = true;
} Else {
Rebox.html (result). show ();
}
Rebox. find ('lil'). bind ('mouseover', function (){
// Lock the prompt layer to ensure that the prompt layer is not closed due to bubbling
Locksuggest = true;
Index = $ (this). index ();
ChangeSelect (index, false );
})
. Bind ('click', function (){
ChangeSelect (index );
SearchSubmit ();
});
Rebox. bind ('mouseout', function (){
Locksuggest = false;
})
} Else {
// If the search result is empty, clear the prompt layer.
Rebox. hide ();
}
}
Function changeSelect (index, v ){
V = false? False: true;
Var obj = rebox. find ('lil'). eq (index );
Rebox. find ('Li. M'). removeClass ('M ');
Obj. addClass ("mo ");
If (v ){
ChoseKey = backval = obj.html ();
Self. val (choseKey );
}
}
Function reSet (){
If (!! Self. val ()){
Index =-1;
Certificate ('{suggest'}.css ('display', 'block ');
Rebox. find ('Li. M'). removeClass ('M ');
// Re-calculate the prompt result Length Based on the html Structure
Rlen = rebox. find ('lil'). size ();
}
}
Function hideResult (){
If (! Locksuggest ){
ChoseKey = backval = null;
Hidden = true;
Rebox. hide ();
}
}
Function searchSubmit (){
Self. val (choseKey );
HideResult ();
ClearInterval (searchtimer );
Formobj. submit ();
}
});
}
}) (JQuery );
Package and download code