AutoComplete implementation principle
It is mainly used on the input and textarea labels to add mouse events to the keyboard listening events and prompt lists.
For example, the input ID is TXT.
Add a keyboard listening event (keyup) for Input)
VaR mindex =-1; $ ("# TXT"). keyup (function (e) {e = E | window. event; If (E. keycode! = 27 & E. keycode! = 38 & E. keycode! = 40) {_ mtxt = $ (this ). val (); fqainit (_ mtxt, _ faqdata); // create a list} If (E. keycode = 27) {// exit with the ESC key $ ("# MList "). remove (); $ (this ). val (_ mtxt);} If (E. keycode = 38) {// key if (mindex>-1) {mindex --;} If (mindex =-1) {mindex = $ ("# MList li "). length-1 ;}$ ("# MList li "). ATTR ("class ",""). eq (mindex ). ATTR ("class", "on"); var choosetxt =$ ("# MList li "). eq (mindex ). text (); $ ("# TXT "). val (choosetxt);} If (E. keycode = 40) {// down key mindex ++; If (mindex = $ ("# MList li "). length) {mindex = 0 ;}$ ("# MList li "). ATTR ("class ",""). eq (mindex ). ATTR ("class", "on"); var choosetxt =$ ("# MList li "). eq (mindex ). text (); $ ("# TXT "). val (choosetxt );}});
Add a mouse event (Mouseover) to the list)
$("#mlist li").live("mouseover",function(){ mindex = $(this).index(); $("#mlist li").attr("class","").eq(mindex).attr("class","on"); var choosetxt = $("#mlist li").eq(mindex).text(); $("#txt").val(choosetxt); });
Create list
Function fqainit (words, arr) {$ ("# MList"). Remove (); // remove the list if ($. Trim (words )! = "") {// Var COUNT = 0 when the content part is empty; // The number of record lists var html = ""; HTML + = "<ul id = 'mlist'>"; for (VAR I = 0, j = arr. length; I <j; I ++) {If (ARR [I]. title. tolocalelowercase (). indexof (words. tolocalelowercase ()))! =-1) {count ++; HTML + = "<li>" + arr [I]. title. replace (words, "<span style = 'color: # ff6666; '>" + words + "</span>") + "</LI> "; if (count> 10) {// display a maximum of 10 breaks; }}} HTML + = "</ul>"; if (count> 0) {// insert $ ("body") into the body if it exists "). append (HTML );}}}