文本框自动匹配提示功能(JQuery-AJAX) 主要思想:当文本框的值每次改变时都异步请求查询数据并返回匹配结果。 前台页面开始时放置一个ul,当异步请求到数据不为空时,循环向ul中添加li标签,并且给li标签添加onclick事件,使得当点击这些li时,把文本框的值设置为当前li的值。并且显示u
2
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | <%@ Page Language= "C#" AutoEventWireup= "true" CodeBehind= "TextAutoFinish.aspx.cs" Inherits= "jQuery.TextAutoFinish" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" > <head runat= "server" > <title></title> <script src= "js/jquery-1.4.2.js" type= "text/javascript" ></script> <script src= "js/jquery-1.4.2-vsdoc.js" type= "text/javascript" ></script> <script type= "text/javascript" > function autoFinish() { //1 TheAshx = "TextSuggestion.ashx" ; //需要异步请求的页面 var key = $( "#txt" ).val(); if (key.length > 0) { //如果文本框有文字才进行异步请求 2 $.post(TheAshx, { "keyword" : key }, function (data, status) { // 3 if (status == "success" ) { //4 var tipText = $.parseJSON(data); var tipHtml = "" ; //拼接HTML标签 //有返回结果才显示 if (tipText.length <= 0) { $( "#tipText" ).hide(); return ; } else $( "#tipText" ).show(); for ( var i = 0; i < tipText.length; i++) { tipHtml += "<li>" + tipText[i] + "</li>" ; } var wid = parseInt($( "#txt" ).width()); var left = parseInt($( "#txt" ).offset().left); var top = parseInt($( "#txt" ).offset().top); var height = parseInt($( "#txt" ).height()); //将拼接好的html代码显示并设置ul的宽度始终与文本框一样 $( "#tipText" ).html(tipHtml).width(wid); //设置ul显示位置始终处于文本框之下。 $( "#tipText" ).css( "position" , "relative" ).css( "left" , left - 10).css( "top" , top + height - 10); $( function () { //5 $( "#tipText" ).addClass( "body" ); $( "#tipText li" ).mouseover( function () { $( this ).css( "background" , "green" ).siblings( "li" ).css( "background" , "white" ); }); $( "#tipText li" ).click( function () { $( "#tipText" ).hide(); $( "#txt" ).val($( this ).text()); }); }) //5 } //4 else { alert( "AJAX错误" ); } }); //3 } //2 } //1 </script> |
1 2 3 4 | <style type= "text/css" > ul{ list-style-type : none ;} .body{ border : 1px solid blue ;} </style> |
1 2 3 4 5 6 7 8 9 10 11 | </ head > < body > < form id = "form1" runat = "server" > < div > < input type = "text" id = "txt" name = "txt" class = "txt" onkeyup = "autoFinish()" style = "width:300px; position:absolute; top:50px; left:50px" /> < ul id = "tipText" style = "margin:0 0 0 0; padding:0 0 0 0; " ></ ul > </ div > </ form > </ body > </ html > |
TextSuggestion.ashx 主要代码:
1 2 3 4 5 6 7 8 9 10 11 | { string key = context.Request[ "keyword" ]; context.Response.ContentType = "text/plain" ; List< string > list = getSuggestionDAL(key); JavaScriptSerializer jss = new JavaScriptSerializer(); string strRes = jss.Serialize(list); context.Response.Write(strRes); |