机票预定中JQuery输入框

前台

var highlightindex = -1; //定义高亮显示索引,-1代表不高亮任何行 
var timeOutId = null; //定义延迟时间Id
var lazeTime = 500; //默认延迟0.5秒
var minPrefix = 0; //定义最小几个字符开始搜索
var mouseOverCss = { background: "white", cursor: " pointer" }; //mouseover
var mouseOutCss = { background: "white" }; //mouseout
var grayCss = { background: "#cef", cursor: " pointer" };
var upDownGrayCss = { background: "#cef" };
var upDownWhiteCss = { background: "white" };

var ajaxProcessUrl = "AutoCompleteHandler.ashx"; //发送ajax请求调用处理url

$(document).ready(function() {
    var wordInput = $("#txtQueryWord");
    var wordInputOffset = wordInput.offset();

    //隐藏自动补全框,并定义css属性
    $("#divAutoList").hide()
              .css("position", "absolute")
              .css("border", "1px black solid") //边框 黑色
              .css("top", wordInputOffset.top + wordInput.height() + 5 + "px")
              .css("left", wordInputOffset.left + "px")
              .width(wordInput.width() + 2);


    //给文本框添加键盘按下并弹起的事件
    wordInput.keyup(function(event) {
        var myEvent = event || window.event;
        var keyCode = myEvent.keyCode;
        var autoNode = $("#divAutoList"); //可供选择的项

        //        if (keyCode >= 65 && keyCode <= 90 || keyCode == 8 || keyCode == 46) { //输入字母,退格或删除,显示最新的内容
        if (keyCode != 13 && keyCode != 38 && keyCode != 40) { //不是三个特殊键,可以搜索
            var wordText = $("#txtQueryWord").val();
            if (wordText.length < minPrefix) return;
            //取消上次提交
            //window.clearTimeout(timeOutId);
            timeOutId = setTimeout(function() {
                //ajax请求
                $.post(ajaxProcessUrl, { KeyWord: wordText }, function(data) {
                    var jqueryObj = $(data);
                    var wordNodes = jqueryObj.find("KeyWord"); //xml节点名
                    autoNode.html("");
                    wordNodes.each(function(i) {
                        var wrodNode = $(this);
                        var newDivNode = $("<div>").attr("id", i);
                        newDivNode.html(wrodNode.text()).appendTo(autoNode); //xml文本内容( wrodNode.text() )
                        //添加光标进入事件, 高亮节点
                        newDivNode.mouseover(function() {
                            if (highlightindex != -1) {
                                $("#divAutoList").children("div")
                                                            .eq(highlightindex)
                                                            .css(mouseOverCss);
                            }
                            highlightindex = $(this).attr("id");
                            $(this).css(grayCss);
                        });

                        //添加光标移出事件,取消高亮
                        newDivNode.mouseout(function() {
                            $(this).css(mouseOutCss);
                        });

                        //添加光标mousedown事件  点击事件newDivNode.click可能不起作用?
                        newDivNode.mousedown(function() {
                            var comText = $(this).text();
                            $("#divAutoList").hide();
                            highlightindex = -1;
                            $("#txtQueryWord").val(comText);
                        });
                    });
                    if (wordNodes.length > 0) {
                        autoNode.show();
                    }
                    else {
                        autoNode.hide();
                        highlightindex = -1;
                    }

                }, "xml"); //xml结果集
            }, lazeTime);
        }
        else if (keyCode == 38) {//输入向上,选中文字高亮
            var autoNodes = $("#divAutoList").children("div")
            if (highlightindex != -1) {
                autoNodes.eq(highlightindex).css(upDownWhiteCss);
                highlightindex--;
            }
            else {
                highlightindex = autoNodes.length - 1;
            }

            if (highlightindex == -1) {
                highlightindex = autoNodes.length - 1;
            }
            autoNodes.eq(highlightindex).css(upDownGrayCss);
        }
        else if (keyCode == 40) {//输入向下,选中文字高亮
            var autoNodes = $("#divAutoList").children("div")
            if (highlightindex != -1) {
                autoNodes.eq(highlightindex).css(upDownWhiteCss);
            }
            highlightindex++;
            if (highlightindex == autoNodes.length) {
                highlightindex = 0;
            }
            autoNodes.eq(highlightindex).css(upDownGrayCss);

        }
        else if (keyCode == 13) {//输入回车
            if (highlightindex != -1) {
                var comText = $("#divAutoList").hide().children("div").eq(highlightindex).text();
                highlightindex = -1;
                $("#txtQueryWord").val(comText);
                return false;
            }
            else {
                alert("文本框中的[" + $("#txtQueryWord").val() + "]被提交了!");
                $("#divAutoList").hide();
                $("#txtQueryWord").get(0).blur();
                return true;
            }
        }
    });

    //给查询框添加blur事件,隐藏提示层
    $("#txtQueryWord").blur(function() {
        $("#divAutoList").hide();
    });

});


后台取值(假)

using System;
using System.Web;
using System.Text;
using System.Threading;

namespace WebTest
{

    public class AutoCompleteHandler : IHttpHandler
    {

        //原文:http://www.cnblogs.com/woodyy/archive/2010/02/03/1662370.html
        public void ProcessRequest(HttpContext context)
        {
            string keyWord = string.Empty;
            if (!string.IsNullOrEmpty(context.Request["KeyWord"]))
            {
                keyWord = context.Request["KeyWord"].Trim();
                ProcessRequest(context, keyWord);
            }
        }

        private void ProcessRequest(HttpContext context, string keyWord)
        {
            try
            {
                context.Response.ClearContent();
                context.Response.ContentType = ("text/xml;charset=UTF-8"); // 这里必须要设置,否则客户端接收不到这里写好的xml文件
                context.Response.Cache.SetCacheability(HttpCacheability.NoCache); //没有缓存
                string result = CreateXmlResult(keyWord);
                context.Response.Write(result);
                context.Response.Flush();
                context.Response.End();
            }
            catch (ThreadAbortException ex)//这个异常不用处理
            {
                string err = ex.Message;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                //Logger.WriteFileLog(ex, Config.logDir);
            }
        }

        /// <summary>
        /// 生成返回提示结果对应的xml文件(实际编程重点关注这里就可以了)
        /// </summary>
        /// <param name="keyWord">实际项目中,应该使用返回的结果集,如泛型集合等等</param>
        /// <returns></returns>
        private string CreateXmlResult(string keyWord)
        {
            StringBuilder sb = new StringBuilder(300);
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<Results>");
            for (int i = 0; i < 10; i++)
            {
                sb.AppendFormat("<KeyWord>{0}_{1}</KeyWord>", keyWord, i);
            }
            sb.Append("</Results>");
            return sb.ToString().Trim();
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

这个是最近跟朋友做的一个项目,用jquery做了个机票的查询的模糊输入框,从网上也查了下,感觉不是都很舒服,用的不少还有BUG,结果跟朋友一块重新写了个,使用这个目前通过我们的后台获得数据也比较快~
本来用JQuery用的少,这个就算是自己JQuery的一个综合性的运用了,用起来的确挺好用的,而且我觉得这个东西也挺好学的。

posted @ 2012-08-31 16:27  Jason_Z  阅读(450)  评论(0)    收藏  举报