天天看點

jquery實作仿google自動補齊

js檔案:

//var autoNode = $("#auto")是錯誤的,因為在外邊隻能聲明變量,不能初始化變量

//因為即使初始化了變量也是不好使的

var autoNode;

var wordNode;    //文本框

var autoChildNodes;

var highlightindex = -1;//文本框高亮顯示的元素的索引,-1表示沒有高亮元素,0則表示第一進制素高亮,1表示第二個元素高亮,以此類推

//設定成-1是因為在數組清單div中,第一個元素索引是0

$(document).ready(function(){

    wordNode = $("#word");

    autoNode = $("#auto");

    autoNode.hide();

//            css("border","1px black solid");

//                     .css("position","absolute")

//                     .css("top",offset.height + wordNode.height)

//                     .css("left",offset.left)

//                     .css("height",offset.height);;

    //處理文本框中的鍵盤事件

    $("#word").keyup(function(event){

        //判斷使用者按下的是哪個鍵

        var myEvent = event || window.event;

        var keycode = myEvent.keyCode;

        //判斷使用者按下的鍵是否是小寫 “a” 到 大寫 "Z"

        if(keycode >= 65 && keycode <= 90 || keycode == 8 || keycode == 46)//8,46是del鍵和backspace鍵,也要向伺服器發送資料

        {

            //1.首先擷取id為word的文本框中的内容

              var wordText = $("#word").val();

              if(wordText != ""){

                //2.向伺服器發送資料,并接受傳回資料,對之進行處理

                $.post("AutoComplete",{word:wordText},function(data){

                    //在處理新接受的資料時,把上一次的内容要清空

                     autoNode.html("");

                     //3.1将dom對象轉化為jquery對象

                    var jqueryObj = $(data);

                    //3.2找到所有的word節點

                    var wordNodes = jqueryObj.find("word");

                    //3.3周遊所有的word節點,取出單詞内容,并把每個節點追加到id為auto的div中

                    wordNodes.each(function(i){

                           //4.1取出單詞内容

                            var text = $(this).text();

                            //4.2新建立一個div節點,并設定節點的内容

                            var divNode = $("<div>").attr("id",i);

                            divNode.html(text);

                            //4.3把建立的div節點追加到對話框中

                            divNode.appendTo(autoNode);

                        //找到所有符合條件的auto節點的<div>子節點

                         autoChildNodes = $("#auto").children("div");

                            //滑鼠進入事件

                            divNode.mouseover(function(){

                                if(highlightindex != -1)

                                {   autoChildNodes.eq(highlightindex).css("background","white");

                                }

                                  $(this).css("background","red");

                                  highlightindex = i;

                            });

                            //滑鼠滑出事件

                            divNode.mouseout(function(){

                                    $(this).css("background","white");

                                    highlightindex = -1;

                            });

                        //滑鼠點選事件,是click函數,而不是onclick函數

                        divNode.click(function(){

                             var clicktext = $(this).html();

                              wordNode.val(clicktext);

                             autoNode.hide();

                            highlightindex = -1;

                             alert("資料" + clicktext +"被發送!");

                        });

                    });

                     var offset = $("#word").offset();

                     autoNode.show()

                             .css("border","1px black solid")

                             .css("position","absolute")

                             .css("top",offset.top + wordNode.height()+4)

                             .css("left",offset.left)

                             .css("width",wordNode.width()+2);

            },"xml");

          }else{

                  autoNode.hide();

                  //對話在關閉的時候就要恢複highlightindex的值為預設值-1

                  highlightindex = -1;

              }

        }else if(keycode == 38 || keycode == 40 ){ //判斷使用者按下的是否是向上鍵(38),還是向下鍵(40)

              if(keycode == 38)

              {//使用者按的是向上的鍵頭

                     if(highlightindex == -1)

                     {

                         highlightindex = autoChildNodes.length-1;

                     }else{

                         autoChildNodes.eq(highlightindex).css("background","white");

                         if(highlightindex == 0)

                         {

                              autoChildNodes.eq(highlightindex).css("background","white");

                              highlightindex= autoChildNodes.length-1

                         }

                         else

                         {

                            highlightindex--;

                         }

                     }

                     autoChildNodes.eq(highlightindex).css("background","red");

              }

              else if(keycode == 40)

              {//使用者按的是向下的鍵頭

                     if(highlightindex == autoChildNodes.length-1)

                     {

                         autoChildNodes.eq(highlightindex).css("background","white")

                         highlightindex = 0;

                     }else{

                         autoChildNodes.eq(highlightindex).css("background","white");

                         highlightindex++;

                     }

                     autoChildNodes.eq(highlightindex).css("background","red");

              }

        }

        else if(keycode == 13)

        {//使用者按下的是Enter鍵

            //下拉框有高亮内容

               if(highlightindex != -1)

               {

                     var text = autoChildNodes.eq(highlightindex).html();

                     wordNode.val(text);

                    autoNode.hide();

                    //對話在關閉的時候就要恢複highlightindex的值為預設值-1

                    highlightindex = -1;

                   alert("資料" + text +"被發送!" );

               }

               else

               {

                    alert("資料" + wordNode.val()+"被發送!" );

                    autoNode.hide();

                    //對話在關閉的時候就要恢複highlightindex的值為預設值-1

                    highlightindex = -1;

               }

             //下拉框沒有高亮内容

        }

    });

    //給按鈕添加事件,因為button沒有id屬性,是以可以

    // 通過$("input[type='button']")的方法來通路到該節點

    $("input[type='button']").click(function(){

          alert("資料"+ $("#word").val()+"被送出!");

    });

});

servlet檔案:

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletException;

import java.io.IOException;

public class AutoComplete extends HttpServlet{

    protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

        doPost(httpServletRequest, httpServletResponse);

    }

    protected void doPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {

       String word = httpServletRequest.getParameter("word");

        //???将字元床儲存在request對象中

        httpServletRequest.setAttribute("word",word);

        //将請求轉發給視圖層,(注意在Ajax中,視圖層并不傳回頁面,隻傳回資料,是以也可稱為資料層)

        httpServletRequest.getRequestDispatcher("wordxml.jsp")

                .forward(httpServletRequest, httpServletResponse);

}

}

word.jsp資料檔案:

<%--

  Created by IntelliJ IDEA.

  User: lucky

  Date: 2009-8-19

  Time: 14:01:13

  To change this template use File | Settings | File Templates.

--%>

<!-- 因為是資料層,是以這裡contentType的類型是text/xml-->

<%@ page contentType="text/xml;charset=UTF-8" language="java" %>

<%

    String word = request.getParameter("word");

%>

<words>

    <%

        if("absolute".startsWith(word)){

    %>

        <word>absolute</word>

    <%

        }

    %>

     <%

        if("abstarct".startsWith(word)){

    %>

        <word>abstarct</word>

     <%

        }

    %>

     <%

        if("anyone".startsWith(word)){

    %>

    <word>anyone</word>

     <%

        }

    %>

     <%

        if("anything".startsWith(word)){

    %>

    <word>anything</word>

     <%

        }

    %>

     <%

        if("anywhere".startsWith(word)){

    %>

    <word>anywhere</word>

     <%

        }

    %>

     <%

        if("brank".startsWith(word)){

    %>

    <word>brank</word>

     <%

        }

    %>

     <%

        if("break".startsWith(word)){

    %>

    <word>break</word>

     <%

        }

    %>

     <%

        if("blank".startsWith(word)){

    %>

        <word>blank</word>

     <%

        }

    %>

</words>

html檔案:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

  <title>自動補全執行個體</title>

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

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

</head>

<body>

    <input type="text" id="word"/>

    <input type="button" value="送出"/><br/>

    <div id="auto"></div>

</body>

</html>

繼續閱讀