jQuery autocomplate 自擴(kuò)展插件、自動完成示例代碼
更新時間:2011年03月28日 19:23:18 作者:
jquery-lib版本是 1.3.2的,該插件是簡單的擴(kuò)展插件,代碼也比較簡單的封裝。所以看起來也比較簡單不是很費(fèi)力,當(dāng)然封裝得也不是很好。
復(fù)制代碼 代碼如下:
不過做了瀏覽器方面的兼容,經(jīng)測試兼容IE6+、Firefox3.5+
首先看看autocomplate.js:
;(function ($) {
var index = -1;
var timeId;
var cssOptions = {
"border": "1px solid black",
"background-color": "white",
"position": "absolute"/*,
"font": "normal normal lighter 14px 6px Times New Roman"*/
};
var defaults = {
width: "auto",
highlightColor: "#3399FE",
unhighlightColor: "#FFFFFF",
css: cssOptions,
dataType: "xml",
paramName: "word",
delay: 500,
max: 20
};
var keys = {
UP: 38,
DOWN: 40,
DEL: 46,
TAB: 9,
ENTER: 13,
ESC: 27,
/*COMMA: 188,*/
PAGEUP: 33,
PAGEDOWN: 34,
BACKSPACE: 8,
A: 65,
Z: 90
};
$.fn.extend({
autocomplete: function (sUrl, settings) {
sUrl = (typeof sUrl === "string") ? sUrl : "";
var param = !this.attr("id") ? defaults.paramName : this.attr("id");
settings = $.extend({}, defaults, {url: sUrl, paramName: param}, settings);
var autoTip = this.autoTipTemplate(this, settings);
$("body").append(autoTip);
var $this = this;
this.keyup(function (event) {
$this.keyOperator(event, autoTip, settings);
});
/*$("input[type=button]").click(function () {
$("#result").text("文本框中的【" + search.val() + "】被提交了!");
$("#auto").hide();
index = - 1;
});*/
return this.each(function () {
$this.val();
});
},
autoTipTemplate: function (input, settings) {
var inputOffset = input.offset();
var autoTip = $("<div/>").css(settings.css).hide()
.css("top", inputOffset.top + input.height() + 5 + "px")
.css("left", inputOffset.left + "px");
var space = $.browser.mozilla ? 2 : 6;//兼容瀏覽器
var tipWidth = (typeof settings.width === "string" && "auto") ? input.width() : settings.width;
autoTip.width(tipWidth + space + "px");
return autoTip;
},
select: function (target, index, settings, flag) {
var color = flag ? settings.highlightColor : settings.unhighlightColor;
target.children("div").eq(index).css("background-color", color);
},
keyOperator: function (event, autoTip, settings) {
var evt = event || window.event;
var autoNodes = autoTip.children("div");
var kc = evt.keyCode;
var $this = this;
/* 當(dāng)用戶按下字母或是delete 或是退格鍵*/
if (kc >= keys.A && kc <= keys.Z || kc == keys.BACKSPACE || kc == keys.DEL) {
var wordText = this.val();
if (wordText.length != 0) {
var param = {};
param[settings.paramName] = wordText;
clearTimeout(timeId);
timeId = setTimeout(function () {
$.post(settings.url, param, function (data) {
var wordObj = $(data);
if (settings.dataType == "xml") {
var wordNodes = wordObj.find("word");
autoTip.html("");
wordNodes.each(function (i) {
var divNode = $("<div>").attr("id", i);
//將遍歷的單詞加入到創(chuàng)建的div中,然后把該div追加到auto中
divNode.html($(this).text()).appendTo(autoTip);
//鼠標(biāo)已進(jìn)去,添加高亮
divNode.mousemove(function () {
//如果已經(jīng)存在高亮,去掉高亮改為白色
if (index != -1) {
autoTip.children("div").eq(index).css("background-color", settings.unhighlightColor);
}
index = $(this).attr("id");
$(this).css("background-color", settings.highlightColor);
});
//鼠標(biāo)移出,取消高亮
divNode.mouseout(function () {
$(this).css("background-color", settings.unhighlightColor);
});
//點(diǎn)擊高亮內(nèi)容
divNode.click(function () {
$this.val($(this).text());
index = -1;
autoTip.hide();
});
});
if (wordNodes.length > 0) {
autoTip.show();
} else {
autoTip.hide();
index = -1;
}
}
});
}, settings.delay);
} else {
autoTip.hide();
index = -1;
}
} else if (kc == keys.UP || kc == keys.DOWN) {/*當(dāng)用戶按下上下鍵*/
if (kc == keys.UP) {//向上
if (index != -1) {
autoNodes.eq(index).css("background-color", settings.unhighlightColor);
index--;
} else {
index = autoNodes.length - 1;
}
if (index == -1) {
index = autoNodes.length - 1;
}
autoNodes.eq(index).css("background-color", settings.highlightColor);
} else {//向下
if (index != -1) {
autoNodes.eq(index).css("background-color", settings.unhighlightColor);
}
index++;
if (index == autoNodes.length) {
index = 0;
}
autoNodes.eq(index).css("background-color", settings.highlightColor);
}
} else if (kc == keys.PAGEUP || kc == keys.PAGEDOWN) {
event.preventDefault();
if (kc == keys.PAGEUP) {
if (index != -1) {
autoNodes.eq(index).css("background-color", settings.unhighlightColor);
}
if (autoNodes.length > 0) {
index = 0;
autoNodes.eq(0).css("background-color", settings.highlightColor);
}
} else {
if (index != -1) {
autoNodes.eq(index).css("background-color", settings.unhighlightColor);
}
index = autoNodes.length - 1;
autoNodes.eq(index).css("background-color", settings.highlightColor);
}
} else if (kc == keys.ENTER) {
//回車鍵
//有高亮內(nèi)容就補(bǔ)全信息
if (index != -1) {
$this.val(autoNodes.eq(index).text());
} else {//沒有就隱藏
$("body").append($("<div/>").text("文本框中的【" + $this.val() + "】被提交了!"));
$this.get(0).blur();
}
autoTip.hide();
index = -1;
} else if (kc == keys.ESC) {
autoTip.hide();
}
}
});
})(jQuery);
現(xiàn)在來分析上面的autocomplate插件的一些常用選項(xiàng):
index就是選擇提示選項(xiàng)高亮的索引;
timeId是當(dāng)用戶在文本域輸入時,利用setTimeout進(jìn)行ajax請求服務(wù)器獲得數(shù)據(jù)的而返回的時間;
cssOptions是自動提示選項(xiàng)的樣式,這里給出了一些默認(rèn)的樣式;
復(fù)制代碼 代碼如下:
var defaults = {
width: "auto",//默認(rèn)或自動設(shè)置寬度
highlightColor: "#3399FE",//高亮?xí)r的顏色
unhighlightColor: "#FFFFFF",//非高亮?xí)r的顏色
css: cssOptions,
dataType: "xml",//ajax請求返回數(shù)據(jù)類型
paramName: "word",//ajax請求的參數(shù)名稱,如果你有設(shè)置文本域的id,那么就使用這個屬性
delay: 500,//當(dāng)文本域在不停的輸入時,ajax多久請求一次服務(wù)器
};
keys就是鍵盤鍵對應(yīng)的值;
autocomplete就是調(diào)用的函數(shù),可以在里面設(shè)置ajax請求的url,以及配置上面defaults中出現(xiàn)的參數(shù),這個方法返回的是文本域的值;
autoTipTemplate就是輸入時顯示的提示框、提示菜單,返回的是一個jquery對象;
select是選擇提示菜單也就是下來提示菜單的高亮選項(xiàng),target當(dāng)然是目標(biāo)對象了,index是即將被高亮的選項(xiàng)的索引,settings就是
高亮的顏色配置,這個在默認(rèn)defaults中就有的。是通過$.extend方法將defaults對象的屬性賦值給settings對象的;
keyOperator是針對文本域的鍵盤操作,這個是核心函數(shù);操作提示、自動補(bǔ)全就靠它了;
下面看看html代碼,看看是如何調(diào)用autocomplate插件的:
復(fù)制代碼 代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Ajax示例,實(shí)現(xiàn)Google搜索補(bǔ)全功能</title>
<meta http-equiv="author" content="hoojo">
<meta http-equiv="email" content="hoojo_@126.com">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="jslib/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jslib/jquery.autocomplete-1.2.js"></script>
<script type="text/javascript">
$(function () {
$(":text").autocomplete("AutocomplataWordServlet", {dataType: "xml", width: "auto"});
});
</script>
</head>
<body>
請輸入:<input type="text" />
<input type="button" value="Go" /><br/><br/>
</body>
</html>
看看這段代碼AutocomplataWordServlet是請求的Servlet,dataType是ajax請求服務(wù)器端的返回數(shù)據(jù)的類型,width可以設(shè)置自動提示菜單的寬度。
怎么樣,用法比較簡單吧。當(dāng)然后面你還可以加其他的配置,如:
代碼片段
復(fù)制代碼 代碼如下:
$(":text").autocomplete("AutocomplataWordServlet", {
width: "auto",
highlightColor: "#3355FE",
unhighlightColor: "#FFFFcc",
css: {border: "2px solid red"},
dataType: "xml",
paramName: "keyWord",
delay: 300
});
這樣也是可以的;
看看AutocomplataWordServlet的代碼:
復(fù)制代碼 代碼如下:
package com.hoo.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@SuppressWarnings("serial")
public class AutocomplataWordServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String word = request.getParameter("word");
request.setAttribute("word", word);
//System.out.println(word);
request.getRequestDispatcher("word.jsp").forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
沒什么可說的,就是獲取客戶端文本域的ajax請求的關(guān)鍵字,然后在jsp頁面中進(jìn)行單詞過濾。不過你也可以在客戶端用正則
或是在服務(wù)器端用正則過濾都是可以的。
下面看看word.jsp的內(nèi)容:
復(fù)制代碼 代碼如下:
<%@ page language="java" contentType="text/xml; charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<words>
<c:if test="${fn:startsWith('abstruct', word)}">
<word>abstruct</word>
</c:if>
<c:if test="${fn:startsWith('anilazine', word)}">
<word>anilazine</word>
</c:if>
<c:if test="${fn:startsWith('appeared', word)}">
<word>appeared</word>
</c:if>
<c:if test="${fn:startsWith('autocytolysis', word)}">
<word>autocytolysis</word>
</c:if>
<c:if test="${fn:startsWith('apple', word)}">
<word>apple</word>
</c:if>
<c:if test="${fn:startsWith('boolean', word)}">
<word>boolean</word>
</c:if>
<c:if test="${fn:startsWith('break', word)}">
<word>break</word>
</c:if>
<c:if test="${fn:startsWith('bird', word)}">
<word>bird</word>
</c:if>
<c:if test="${fn:startsWith('blur', word)}">
<word>blur</word>
</c:if>
<c:if test="${fn:startsWith('call', word)}">
<word>call</word>
</c:if>
<c:if test="${fn:startsWith('class', word)}">
<word>class</word>
</c:if>
<c:if test="${fn:startsWith('card', word)}">
<word>card</word>
</c:if>
<c:if test="${fn:startsWith('dacnomania', word)}">
<word>dacnomania</word>
</c:if>
<c:if test="${fn:startsWith('document', word)}">
<word>document</word>
</c:if>
</words>
就是一個xml格式的文檔,通過使用jstl表達(dá)式,用startsWith函數(shù)匹配,如果通過就顯得在xml內(nèi)容中,還有看到上面的contentType="text/xml; charset=UTF-8"了沒有,是text/xml哦!這點(diǎn)要注意,如果不設(shè)置有的瀏覽器就不能解析了。
作者:hoojo
blog:http://blog.csdn.net/IBM_hoojo
您可能感興趣的文章:
- jQuery插件擴(kuò)展實(shí)例【添加回調(diào)函數(shù)】
- jQuery插件擴(kuò)展extend的簡單實(shí)現(xiàn)原理
- jQuery插件擴(kuò)展測試實(shí)例
- jQuery插件formValidator自定義函數(shù)擴(kuò)展功能實(shí)例詳解
- jQuery插件kinMaxShow擴(kuò)展效果用法實(shí)例
- jquery事件機(jī)制擴(kuò)展插件 jquery鼠標(biāo)右鍵事件
- JQuery模板插件 jquery.tmpl 動態(tài)ajax擴(kuò)展
- boxy基于jquery的彈出層對話框插件擴(kuò)展應(yīng)用 彈出層選擇器
- jQuery下擴(kuò)展插件和拓展函數(shù)的寫法(匿名函數(shù)使用的典型例子)
- jquery.boxy插件的iframe擴(kuò)展代碼
- 利用jQuery插件擴(kuò)展識別瀏覽器內(nèi)核與外殼的類型和版本的實(shí)現(xiàn)代碼
- jQuery插件擴(kuò)展操作入門示例
相關(guān)文章
jackson解析json字符串,首字母大寫會自動轉(zhuǎn)為小寫的方法
下面小編就為大家分享一篇jackson解析json字符串,首字母大寫會自動轉(zhuǎn)為小寫的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2017-12-12jQuery實(shí)現(xiàn)帶滾動線條導(dǎo)航效果的方法
這篇文章主要介紹了jQuery實(shí)現(xiàn)帶滾動線條導(dǎo)航效果的方法,分析了帶滾動條導(dǎo)航效果的實(shí)現(xiàn)原理與相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-01-01JQuery獲取元素文檔大小、偏移和位置和滾動條位置的方法集合
在ajax中經(jīng)常需要對元素的位置進(jìn)行精確的定位,此時不僅需要獲取元素自身的大小位置等屬性。還需要知道頁面、瀏覽器、滾動條等的長度和寬度。2010-01-01jQuery 文本框得失焦點(diǎn)的簡單實(shí)例
本篇文章主要是對jQuery 文本框得失焦點(diǎn)的簡單實(shí)例進(jìn)行了介紹,需要的朋友可以過來參考下,希望對大家有所幫助2014-02-02jquery實(shí)現(xiàn)圖片上傳前本地預(yù)覽
這篇文章主要為大家詳細(xì)介紹了jquery實(shí)現(xiàn)圖片上傳前本地預(yù)覽功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04基于jQuery實(shí)現(xiàn)的水平和垂直居中的div窗口
在建立網(wǎng)頁布局的時候,我們經(jīng)常會面臨一個問題,就是讓一個div實(shí)現(xiàn)水平和垂直居中,雖然好幾種方式實(shí)現(xiàn),但是今天介紹時我最喜歡的方法,通過css和jQuery實(shí)現(xiàn)。2011-08-08