I have watched Jquery over the past few days. This series is well written in the blog of Zhang Ziqiu. I would like to praise it here. After reading so many things, it is only necessary to convert them into actual results. Otherwise, it is just a matter of white reading and white learning. That's exactly the case. A retrieval system was built some time ago, with hundreds of servers Haha. Now we have this requirement. The following prompt is displayed automatically when you enter the indicator.
Okay, the background is clear. Not that much nonsense.
In fact, the principle is very clear to everyone. Users enter a word in the text box, then use ajax to search from the backend server, assemble it, and return it to the page. The page is parsed using javascript, it is displayed in a layer. The principle seems to be too simple. Everyone can say this if they know ajax. But, to be honest, when you do it yourself, you will find many problems, okay. Check the code first.
Var $ autocomplete = $ ("<ul class = 'autocomplete'> </ul>"). hide (). insertAfter ("# search-text ");
$ ("# Search-text"). keyup (function (){
$. Get ("e. aspx", {"search-text": $ ("# search-text"). val ()}, function (data ){
If (data. length ){
$ Autocomplete. empty ();
Var arr = data. substring (0, data. length-1). split (',');
$. Each (arr, function (index, term ){
$ ("<Li> </li>"). text (term). appendTo ($ autocomplete). mouseover (function (){
Certificate (this).css ("background", "green ");
}). Mouseout (function (){
Certificate (this).css ("background", "white ");
})
. Click (function (){
$ ("# Search-text"). val (term );
$ Autocomplete. hide ();
});
});
$ Autocomplete. show ();
}
});
}). Blur (function (){
SetTimeout (function (){
$ Autocomplete. hide ();
},500 );
});
The problem mainly occurs in these two aspects. First, the data returned by ajax is displayed in the layer, and how to select and fill it in the text box by clicking, the above code has been resolved. The second problem is troublesome. When the user inputs a keyword and then wants to operate somewhere else, the text box loses focus and the drop-down layer should be hidden. However, a blur event always occurs before the click event. When you click the drop-down layer, the focus of the text box will be lost, so this function cannot be completed. Here, I used setTimeout for reference to foreign documents to delay the hide of the drop-down layer. In this way, the function is complete.
Here, I want to give you a brief introduction. jquer is really powerful. I love it. Haha.