自动完成

来源:互联网 发布:微信软件登陆 编辑:程序博客网 时间:2024/05/15 23:13

下面是一个自动完成的例子,其中第一个文本框中输入RC【其值是从数据库中取得的】,第二个文本框中的值是根据前一个文本框中的RC动态加载的【动态的从数据库中去】。

提醒:用XMLHttpRequest访问后台时,一般最先执行的是Page_Load(object sender, EventArgs e), 这说明XMLHttpRequest访问后台时,相当于重新访问了整个.cs文件【可以理解为后台刷了,但前台浏览器不刷页面】,
所以XMLHttpRequest  访问后台时Page.IsPostBack一直为false,但用AjaxPro,你是从前台脚本以“类名.方法名”的形式调用,所以他直接执行你调用的方法,不理睬Page_Load(object sender, EventArgs e),这是这两种方式访问后台时的区别

AutoCompeletTextBox.aspx :
【注意要吧vs2005自动生成的<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">要去掉】

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AutoCompeletTextBox.aspx.cs"
    Inherits
="Test_AutoCompeletTextBox" 
%>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>无标题页</title>
    
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
    
<style>
.sdiv
{font-size:12px;overflow-y:auto;overflow-x:hidden;height:expression(this.parentElement.style.pixelHeight);z-index:101;}
.sdivover
{background:highlight;color:highlighttext;width:100%;padding-left:3px;cursor:default;overflow:hidden;hidden;line-height:120%;}
.sdivout 
{background:#FFFFFF;color:#000000;width:100%;padding-left:3px;cursor:default;overflow:hidden;line-height:120%;}
input
{haiwa:expression(this.onkeyup=__ACP);hw:expression(this.ondblclick=__ACP);}
</style>
</head>
<body onclick="divclick()" onkeydown="KeyDown()">
    
<form id="form1" runat="server">

        
<script language="JavaScript">
<!--
var xmlhttp;
var __InputName;
var HighLine = 0
var MenuStrs = ""
var MenuLines = 0
var KeyOnMenu = false
var _AutoObj
var ShowLine = 10
var LineHeight = 15
var SelectValue = "";
var __InputName;
function DivOver(obj){
    
if (KeyOnMenu){
        updateHtml(
-1);
        KeyOnMenu 
= false
    }

    obj.className
="sdivover";
}


function divclick(obj){
    document.getElementById(
"__AutocompleteDiv").style.display = "none";
    
if (obj){
        selectedvalue 
= obj.innerText;
        __InputName.value 
= selectedvalue;
    }

    HighLine 
= 0
    _Autostr 
= ""
    SelectValue 
= ""
}

function __ACP(){
    
if (event.keyCode!=13){
        event.cancelBubble
=true
        e 
= this;
        
var t=e.offsetTop; 
        
var l=e.offsetLeft; 
        
var w=e.offsetWidth;
        
var h=e.offsetHeight;
        _AutoObj 
= this
        divID 
= document.getElementById("__AutocompleteDiv");
        __InputName 
= this;
        updateHtml(HighLine);
        
if (MenuLines>0){
            
while(e=e.offsetParent)
            

                t
+=e.offsetTop; 
                l
+=e.offsetLeft; 
            }

            divID 
= eval(divID);
            divID.style.top 
= t+h;
            divID.style.left 
= l;
            divID.style.width 
= w;
            divID.style.height 
= MenuLines * LineHeight>ShowLine*LineHeight?ShowLine*LineHeight:MenuLines * LineHeight;
            divID.style.display 
= ""
        }

        
else{
            divID.style.display 
= "none"
        }

    }

}

function InsertSort(arr) //插入排序->直接插入法排序@panliu888
    var temp, j;
    
for(var i=1; i<arr.length; i++{
        
if((arr[i]) < (arr[i-1])) {
            temp 
= arr[i];
            j 
= i-1;
            
do {
                arr[j
+1= arr[j];
                j
--;
            }

            
while (j>-1 && (temp) < (arr[j]));
            arr[j
+1= temp;
        }
//endif
    }

    
return arr;
}

function updateHtml(k){
     listhtml 
= ""
    
var line = 0
    htmlarr 
= InsertSort(_AutoObj.autolist.split("|"))
    
var liststrarr = htmlarr;
    
for(i=0;i<liststrarr.length;i++){
        
if((liststrarr[i].substr(0,_AutoObj.value.length).toLowerCase()==_AutoObj.value.toLowerCase())&&(liststrarr[i].length>_AutoObj.value.length)){
            line 
++;
            
if (k==line){
                SelectValue 
= liststrarr[i]
                listhtml 
+= '<div class="sdivover" onclick="divclick(this)" onmouseover=DivOver(this);HighLine='+line+';SelectValue="'+liststrarr[i].replace(/"/ig,"/&#34")+'"; onmouseout=this.className="sdivout";>'+liststrarr[i]+'</div>';
            }
            else
                listhtml += 
'<div class="sdivout" onclick="divclick(this)" onmouseover=DivOver(this);HighLine='+line+';;SelectValue="'+liststrarr[i].replace(/"/ig,"/&#34")+'"; onmouseout=this.className="sdivout";>'+liststrarr[i]+'</div>';
        }
    }
    MenuLines = line
    document.getElementById("__AutocompleteDivlist").innerHTML = listhtml;
    document.getElementById("__AutocompleteDivlist").scrollTop = (k-ShowLine)>0?(k-ShowLine)*LineHeight:0;
}
function KeyDown(){
    switch ( event.keyCode ){
        case 13 : if(SelectValue.length>0){_AutoObj.value =SelectValue;divclick();}break ;
        case 38 : KeyMove(-1) ;    break ;
        case 40 : KeyMove(1) ;    break ;
    }
}
function KeyMove(n){
    HighLine = HighLine+(n);
    if (parseInt(HighLine)>parseInt(MenuLines)){HighLine = 1;}
    if(parseInt(HighLine)<1){HighLine = MenuLines;}
    KeyOnMenu = true;
    updateHtml(HighLine)
}
function CreateXMLHttpRequest()
    {
        if (window.ActiveXObject)
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if (window.XMLHttpRequest)
        {
            xmlhttp = new XMLHttpRequest();
        }
    } 
function send(arg)
    {
       CreateXMLHttpRequest();
       xmlhttp.onreadystatechange = fillItem;
       xmlhttp.open("GET","AutoCompeletTextBox.aspx?rc=" + arg ,true);
       xmlhttp.send(null);
    }
function getrcItem()
{
    var inputrc = document.getElementById("tbRC").value;
    if (inputrc.length == 0)
    return;
    send(inputrc);
}
function fillItem()
{
     if (xmlhttp.readyState == 4)
        {
            if(xmlhttp.status == 200)
            {
                 var obj = document.getElementById("tbItem");
                 obj.setAttribute("autolist",xmlhttp.responseText);
            }
        }
}
//-->
        </script>

        昵称:<input type="text" size="40" name="q" runat="server" id="tbRC" onblur="return getrcItem(this.value);"
            autocomplete="off"><br>
        网址:<input type="text" size="40" name="q" runat="server" id="tbItem" autocomplete="off">
        <div id="__AutocompleteDiv" style="position: absolute; border: 1 solid #000000; display: none;
            height: 180px; background: #FFFFFF;" onclick="event.cancelBubble=true">
            <div class="sdiv" id="__AutocompleteDivlist" onclick="event.cancelBubble=true">
            </div>
        </div>
    </form>
</body>
</html>
utoCompeletTextBox.aspx.cs :

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Test_AutoCompeletTextBox : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    
{
        
if (!Page.IsPostBack)
            
this.tbRC.Attributes["autolist"= AllRCs();
        
if (Request.QueryString["rc"== null || Request.QueryString["rc"].ToString().Length == 0)
            
return;
        
else
        
{
            
string inputrc = Request.QueryString["rc"].ToString();
            Response.Write(RCtoItem(inputrc));
            Response.Flush();
            Response.Close();
        }

    }


    
private string AllRCs()
    
{
        
string allrcs = "";
        DataTable rcs 
= com.topcheer.ETSOperatLogic.Param.getAllRc();
        
if (rcs.Rows.Count == 0)
            
return "";
        
foreach (DataRow dr in rcs.Rows)
        
{
            allrcs 
+= dr[1].ToString() + "|";
        }

        
return allrcs.TrimEnd('|');
    }

    
private string RCtoItem(string rc)
    
{
        
string tempitems = "";
        DataTable items 
= com.topcheer.ETSOperatLogic.Param.getItemByRc(rc);
        
if (items.Rows.Count == 0)
            
return "";
        
foreach (DataRow dr in items.Rows)
        
{
            tempitems 
+= dr[1].ToString() + "|";
        }

        
return tempitems.TrimEnd('|');
    }

}

注意:XMLHttpRequest请求CS文件时相当于第一次请求,所以他不会理睬Page.IsPostBack属性
其中标签<input 用到了自定义的属性autolist,要使其形式成为autolist="51windows|&#34|haiwa|blueidea|hw|google|jimao8|中国|中|海娃|李海华",这是要在自动完成时预置的自动完成项。

原创粉丝点击