Jquery 自動完成控制元件

wl1121發表於2009-05-22

/*
 * jQuery AutoComplete
 *
 * Author: cntlis
 * http://blog.csdn.net/cntlis
 *
 * Licensed like jQuery, see http://docs.jquery.com/License
 *
 * 作者:cntlis
 * QQ:8112857
 */
$.fn.AutoComplete = function(url,option){
	var me= this;
	var strKey= $(me).val();
	var strKeyBak= "";
	var isShow = false;
	var doption={
		iwidth: '0px',	//下拉框的寬度
		iLengthLower: 1,	//當表單的長度大於iLengthLower小於iLengthUpper時才開始執行搜尋
		iLengthUpper: 50,
		strPara: "Keyword",	//變數名稱
		zIndex: 1,	//提示框的Z-INDEX值
		hasscroll: 0,	//是否出現滾動條0無1有
		hasclose: 1,	//是否擁有關閉視窗
		desfun:function(){}
	};
	
	$.extend(doption,option);	
	var iLengthLower= doption.iLengthLower;
	var iLengthUpper= doption.iLengthUpper;
	var strPara= doption.strPara;
	if ($("#autocomplete").length<1){$("body").append("<div id='autocomplete' class='autocompletefloor'></div>");}
	$("#autocomplete").hide();
	
	$(me).keyup(function(e){keysearch(e.keyCode);});
	$(me).keydown(function(e){LineSelect(e.keyCode);});
	$(me).bind("blur",function(){
		strKeyBak= $("#autocomplete ul .selected .keyname").text();	//為click事件增加處理
		if (strKeyBak.length>0 && strKeyBak!=$(me).val()){
			$(me).val(strKeyBak);
			doption.desfun();
		};
		floorHide();
	});
	
	var encode=function(v){//如果包含中文就escape,避免重複escape)
  return escape(v).replace(/\+/g, '%2B').replace(/\"/g,'%22').replace(/\'/g, '%27').replace(/\//g,'%2F');
 }
	
	function floorHide(){
		$("#autocomplete").hide().html("");
		strKey= "";
		isShow = false;
	}
	
	function floorShow(){
		var p= $(me).offset();
		var w= (doption.iwidth == "0px") ? $(me).width()+2 : doption.iwidth;
		$("#autocomplete").css({
		 'z-index:':doption.zIndex,
		 width:w,
		 top:parseInt(p.top+$(me).outerHeight())+"px",
		 left:parseInt(p.left)+"px"
	 }).show();
		strKey= "";
		isShow = true;
	}
	
	function keysearch(code){
		var strKeyNow=$(me).val();
		if(code == 38 || code == 40 || code == 13 || code == 27 || code == 9) return;    //TAB/回車、ESC、向上、向下
		if((strKey == "" || strKeyNow != strKey) && strKeyNow.length >= iLengthLower && strKeyNow.length <= iLengthUpper){
			$.ajax({
				type: "Get",
				dataType: "json",
				url: url,
				data: strPara != "" ? strPara + "=" + encode(strKeyNow) : "",
				success: function(json){
					json=json.keylist;
					if (json.length>0){
						//獲取搜尋資料
						var strContent= "<ul>";
						$.each(json, function(i, n){
							if(n.keyname.length>0){	//如果
								//alert(n.keyname);
								strContent+= '<li class="keyinfo"><span class="keyname">'+n.keyname+'</span>';
								try{
								if (n.keyextend.length>0){strContent+='<span class="keyextend">'+n.keyextend+'</span>';}
								}catch(E){};
								strContent+= '</li>';
							};
						});
						if (doption.hasclose==1){
							strContent+= '<li class="close"><span>關閉</span></li>';
						}
						strContent+='</ul>';
						$("#autocomplete").html(strContent);
						$("#autocomplete .keyinfo").mouseover(function(){$("#autocomplete .selected").removeClass("selected");$(this).removeClass("unselected").addClass("selected");}).mouseout(function(){$(this).removeClass("selected").addClass("unselected");}).click(function(){if(strKeyBak.length()>0){$(me).val(strKeyBak);}});
						floorShow();
					}else{
						//沒有搜尋資料
						floorHide();
						return;
					}
				}
			});
			strKey=$(me).val();
		}
		if(strKey.length == 0 || strKey.length <= iLengthLower || strKey.length >= iLengthUpper) floorHide();
	}
	
	function LineSelect(code){
		if(code == 27){floorHide();};//Enter鍵、ESC鍵
		if(code == 13){floorHide();doption.desfun();};
		if(!isShow) return;
		ObjSelected=$("#autocomplete ul .selected");
		if (ObjSelected.length>0){	//如果已經有選定
			//alert('dasfdas');
			if(code == 38){	//向上鍵
				if(ObjSelected.prev().text() != ""){	//如果不是第一個資料
					ObjSelected.removeClass("selected").addClass("unselected").prev().removeClass("unselected").addClass("selected");
					$(me).val($("#autocomplete ul .selected .keyname").text());
				}else{
					ObjSelected.removeClass("selected").addClass("unselected");
					$("#autocomplete .keyinfo:last").removeClass("unselected").addClass("selected");
					$(me).val($("#autocomplete ul .selected .keyname").text());
				}
			}else if (code == 40){	//向下鍵
				if(ObjSelected.next().text() != ""){	//如果不是第一個資料
					ObjSelected.removeClass("selected").addClass("unselected").next().removeClass("unselected").addClass("selected");
					$(me).val($("#autocomplete ul .selected .keyname").text());
				}else{
					ObjSelected.removeClass("selected").addClass("unselected");
					$("#autocomplete .keyinfo:first").removeClass("unselected").addClass("selected");
					$(me).val($("#autocomplete ul .selected .keyname").text());
				}
			}
		}else if(code == 38){
				$("#autocomplete .keyinfo:last").removeClass("unselected").addClass("selected");
				$(me).val($("#autocomplete .keyinfo:last .keyname").text());
		}else if(code == 40){
				$("#autocomplete .keyinfo:first").removeClass("unselected").addClass("selected");
				$(me).val($("#autocomplete .keyinfo:first .keyname").text());
		}
	}
}

 以上為complete.js

新增引用

<script src="../js/jquery-latest.js" type="text/javascript"></script>
 

    <script src="../js/complete.js" type="text/javascript"></script>

 新增樣式

*
        {
            margin: 0px;
            padding: 0px;
        }
        #autocomplete
        {
            border: 1px solid #000;
            position: absolute;
            background-color: #fff;
        }
        /*每行的格式*/#autocomplete li
        {
            display: block;
            text-align: left;
            height: 20px;
            line-height: 20px;
            background-color: #fff;
            cursor: default;
            padding: 0 5px;
            clear: both;
        }
        /*滑鼠選中時的格式*/#autocomplete .selected
        {
            background-color: #565da9;
            color: #fff;
            overflow: hidden;
        }
        /*滑鼠離開時代格式*/#autocomplete .unselected
        {
            background-color: #fff;
            color: #666;
        }
        /*關鍵字資訊*/#autocomplete .keyname
        {
            display: block;
            float: left;
        }
        /*關鍵字擴充套件資訊*/#autocomplete .keyextend
        {
            display: block;
            float: right;
            color: green;
        }
        #autocomplete .unselected .keyextend
        {
            color: green;
        }
        #autocomplete .selected .keyextend
        {
            color: #fff;
        }
        /*關閉*/#autocomplete .close
        {
            text-align: right;
        }
        #autocomplete .close span
        {
            color: blue;
            cursor: pointer;
            text-decoration: underline;
        }

 使用

 $("#<%=txtsupplierId.ClientID %>").AutoComplete("AddApplication.ashx?key=" + $("#<%=txtsupplierId.ClientID %>").val() + "&action=supplier", "");

 後臺程式碼

    private void AutoAddSuplier(string keyWords)
    {
        Response.Write("{'keylist':[");
        for (int i = 0; i < 10; i++)
        {
            Response.Write("{'keyname':'" + keyWords + i + "','keyextend':''},");
        }
        Response.Write("{'keyname':'" + keyWords + "10'}]}");
    }
 

相關文章