java+jquerygoogle百度搜索自动提示效果
自动补齐功能的实现(仿google、百度搜索框)
else if (window.ActiveXObject) { // IE浏览器
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
}
}
function suggestOver(div_value){
div_value.className = "suggest_link_over";
}
function suggestOut(div_value){
div_value.className = "suggest_link";
<ቤተ መጻሕፍቲ ባይዱhtml>
2.1,Server.aspx(数据提供页,此页面中删除其它多余代码,只留最上面一行。如果这里改了名请记得显示页面的调用处也要改哈-_-)
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Server.aspx.cs" Inherits="Server" %>
padding: 2px 6px 2px 6px;
}
.suggest_link_over
{
background-color: #E8F2FE;
padding: 2px 6px 2px 6px;
}
#search_suggest
var s='<div onmouseover="javascript:suggestOver(this);"';
利用JavaScript和ASP.NET获取各大搜索引擎的自动提示
可 以看 出返 回结 果是 J S O N P格 式 的 结 果 ,在 实 际 应 用 程 序 中 ,可 以 在 回调 函 数 中 对 返 回 的 J S O N P结 果 进 行 解 析 f P a r s e ) 成 具 体 应 用 程 序需 要 的格 式 。 以 下 是输 入一 个 关 键 字 并 通 过 回
A S 4 I I I I I H C S ” : 0 . 0 4 8 9 4 3 } , { ¨ T x t “ : “ 微软杀 毒“ . “ T V p e “ : “ A S ” , ” S k ” : “ A S 5 “ , ”
输 入 ,同 时也 是引 导用 户 搜索 的工 具 ,尤 其是 对于 搜索 意 图不 是 很 明确 的用 户 。既 然是 引 导用 户 的工具 ,那 么 它就 可 以应 用于 其 他 的 网 站 和 应 用 了 。 最典 型 的 就 是 各 大 中小 网站 的 站 内搜 索 , 可 以借 用 搜 索 引擎 提示 的 自动 提 示服 务 来提 高 网站 用 户 的体 验 。
A S n , i i S k ” : AS I “ , “ H C S ” : 0 . 3 2 1 3 9 5 } , { ¨ T x t “ : “微 软 中 国 ” , “ T v p e “ : “ A S ” , ”
S k ” : ” A S 2 “ , “ H C S “ : 0 . 3 9 5 8 8 6 } , { l I T x t ” : “微 软 杀 毒 软 件 ” , “ T v p e “ : “ A S “ , S k ” : ” A S 3 I I I I H C S “ : 0 . 0 5 3 1 7 9 } , { ¨ T x t ” : ”微 软 官 网 ” , ” T v p e ” : “ AS “ , “ S k H = I l
JQERY AUTOCOMPLENT类似百度GOOLE搜索功能
利用JQUERY AUTOCOMPLENT 实现类似百度和GOOLE 搜索地功能例子:JSP :<%@page language="java"import="java.util.*"pageEncoding="UTF-8"%> <%String path = request.getContextPath();String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServ erPort()+path+"/";%><!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma"content="no-cache"><meta http-equiv="cache-control"content="no-cache"><meta http-equiv="expires"content="0"><meta http-equiv="keywords"content="keyword1,keyword2,keyword3"> <meta http-equiv="description"content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript"src="js/jquery.js"></script><script type='text/javascript'src='js/jquery.autocomplete.js'></script><link rel="stylesheet"type="text/css"href="js/jquery.autocomplete.css"/><script language="javascript"type="text/javascript">$(document).ready((function () {function format(mail) {return ;}$("#txtUser").autocomplete("test_test.action",{multiple: true,dataType: "json",multipleSeparator:"",parse: function(data) {return $.map(data, function(row) {return {data: row,value: ,result: }});},formatItem: function(item) {return format(item);}}).result(function(e, item){$("#content").append("<p>selected " + format(item) + "</p>");});}));</script></head><body><div>省份:<input id="txtProvince"type="text"/>TEST:<input id="txtUser"type="text"/></div></body></html>后台ACTIONpublic class Test extends ActionSupport {private String q;public String test() throws Exception{JSONObject jot = new JSONObject();JSONArray jsonArray = new JSONArray();System.out.println(q);DateaBaceConnection dbc = new DateaBaceConnection();String hql = "select id,name from user where name like ?";Connection con = dbc.getConnection();System.out.println(dbc);PreparedStatement pst = con.prepareStatement(hql);pst.setString(1, "%"+ q +"%");ResultSet rs = pst.executeQuery();while(rs.next()){ System.out.println("+++++++++++++++++++++++");System.out.println("====================="+rs.getInt(1));JSONObject jo = new JSONObject();jo.put("id", rs.getInt(1));jo.put("name", rs.getString(2));jsonArray.add(jo);}jot.put("array", jsonArray);System.err.println(jsonArray.size());HttpServletResponse r = ServletActionContext.getResponse();r.setContentType("text/html;charset=UTF-8");PrintWriter out = r.getWriter();out.print(jsonArray);out.flush();out.close();return null;}public String getQ() {return q;}public void setQ(String q) {this.q = q;}}JQUERY AUTOCOMPLENT 提交地参数为qACTION 返回必须为JSON对象。
仿百度的输入框自动提示
今天在项目中碰到一个需求,就是在input输入框中录入数据时(名字),假如敲入了一部分,在数据库中存在已有的姓名的前缀与之匹配,就弹出一个 googl e页面那种效果的下拉框,把相关的姓名列出来供他选择。
可以用箭头上下选择,也可以用鼠标选择。
这样可以提高录入的效率。
输入框的布局如下:最终的效果如下:表单中输入框的html代码为:<tr><td>发件人</td><td><input type="text" name="sendername" id="sendername" value="" /></td></tr>为了在输入一些内容时,能够显示出那个选择框,我们要建立一个div,初始时不可见,当需要时就显示出来,并且将它移动到正确的位置。
这个div采用的定位为绝对定位,这样就可以在整个页面用left和top来定位了,z-index为99,这样就可以盖住下面的东西。
选择框的div为:<div id="helper" class="gac_m" style="visibility:hidden;" width="100%" ></div>gac_m的css定义为:.gac_m {background:white none repeat scroll 0 0;border:1px solid black;cursor:default;font-size:13px;line-height:17px;margin:0;position:absolute;z-index:99;width:100px;left:10px;top:10px;}当需要显示时,我们需要将id为helper的div移动到正确的位置,这个位置就是input输入框的正下方,left即为input的相对页面左边的位移,top即为inp ut相对页面上边的位移加上input本身的高度。
php+ajax做仿百度搜索下拉自动提示框(2)
php+ajax做仿百度搜索下拉自动提示框(2)php+ajax做仿百度搜索下拉自动提示框--CREATE TABLE IF NOT EXISTS `countries` (`id` int(6) NOT NULL auto_increment,`value` varchar(250) NOT NULL default '',PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=243 ;---- 转存表中的数据 `countries`--INSERT INTO `countries` (`id`, `value`) VALUES(1, 'Afghanistan'),(2, 'Aringland Islands'),(3, 'Albania'),(4, 'Algeria'),(5, 'American Samoa'),(6, 'Andorra'),(7, 'Angola'),(8, 'Anguilla'),(9, 'Antarctica'),(10, 'Antigua and Barbuda'),(11, 'Argentina'),(12, 'Armenia'),(13, 'Aruba'),(14, 'Australia'),(15, 'Austria'),(16, 'Azerbaijan'),(17, 'Bahamas'),(18, 'Bahrain'),(19, 'Bangladesh'),(20, 'Barbados'),(21, 'Belarus'),(22, 'Belgium'),(23, 'Belize'),(24, 'Benin'),(25, 'Bermuda'),(26, 'Bhutan'),(27, 'Bolivia'),(28, 'Bosnia and Herzegovina'), (29, 'Botswana'),(30, 'Bouvet Island'),(31, 'Brazil'),(32, 'British Indian Ocean territory'), (33, 'Brunei Darussalam'),(34, 'Bulgaria'),(35, 'Burkina Faso'),(36, 'Burundi'),(37, 'Cambodia'),(38, 'Cameroon'),(39, 'Canada'),(40, 'Cape Verde'),(41, 'Cayman Islands'),(42, 'Central African Republic'), (43, 'Chad'),(44, 'Chile'),(45, 'China'),(46, 'Christmas Island'),(47, 'Cocos (Keeling) Islands'), (48, 'Colombia'),(49, 'Comoros'),(50, 'Congo'),(51, 'Congo'),(52, ' Democratic Republic'), (53, 'Cook Islands'),(54, 'Costa Rica'),(55, 'Ivory Coast (Ivory Coast)'), (56, 'Croatia (Hrvatska)'), (57, 'Cuba'),(58, 'Cyprus'),(59, 'Czech Republic'),(60, 'Denmark'),(61, 'Djibouti'),(62, 'Dominica'),(63, 'Dominican Republic'), (64, 'East Timor'),(65, 'Ecuador'),(66, 'Egypt'),(67, 'El Salvador'),(68, 'Equatorial Guinea'), (69, 'Eritrea'),(70, 'Estonia'),(71, 'Ethiopia'),(72, 'Falkland Islands'), (73, 'Faroe Islands'),(74, 'Fiji'),(75, 'Finland'),(76, 'France'),(77, 'French Guiana'),(78, 'French Polynesia'),(79, 'French Southern Territories'), (80, 'Gabon'),(81, 'Gambia'),(82, 'Georgia'),(83, 'Germany'),(84, 'Ghana'),(85, 'Gibraltar'),(86, 'Greece'),(87, 'Greenland'),(88, 'Grenada'),(89, 'Guadeloupe'),(90, 'Guam'),(91, 'Guatemala'),(92, 'Guinea'),(93, 'Guinea-Bissau'),(94, 'Guyana'),(95, 'Haiti'),(96, 'Heard and McDonald Islands'), (97, 'Honduras'),(98, 'Hong Kong'),(99, 'Hungary'),(100, 'Iceland'),(101, 'India'),(102, 'Indonesia'),(103, 'Iran'),(104, 'Iraq'),(105, 'Ireland'),(106, 'Israel'),(107, 'Italy'),(108, 'Jamaica'),(109, 'Japan'),(110, 'Jordan'),(111, 'Kazakhstan'),(112, 'Kenya'),(113, 'Kiribati'),(114, 'Korea (north)'),(115, 'Korea (south)'),(116, 'Kuwait'),(117, 'Kyrgyzstan'),(118, 'Lao People''s Democratic Republic'), (119, 'Latvia'),(120, 'Lebanon'),(121, 'Lesotho'),下载文档。
基于jquery的搜索框输入提示
基于jquery的搜索框输⼊提⽰仿百度与google的搜索框输⼊提⽰,⽀持键盘上下选择与⿏标点击选择。
只包含前⾯代码,后台返回数据为模拟的数据。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>搜索</title><meta name="description" content=" 内容介绍不超过100个中⽂"><meta name="keywords" content=" 内容相关关键词3-5个"><link href="index.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="jquery-1.4.3.min.js"></script></head><body><div class="gover_search"><div class="gover_search_form clearfix"><span class="search_t">关键词匹配搜索</span><input type="text" class="input_search_key" id="gover_search_key" placeholder="请输⼊关键词直接搜索" /><button type="submit" class="search_btn">搜索</button><div class="search_suggest" id="gov_search_suggest"><ul></ul></div></div></div><script type="text/javascript">//实现搜索输⼊框的输⼊提⽰js类function oSearchSuggest(searchFuc){var input = $('#gover_search_key');var suggestWrap = $('#gov_search_suggest');var key = "";var init = function(){input.bind('keyup',sendKeyWord);input.bind('blur',function(){setTimeout(hideSuggest,100);})}var hideSuggest = function(){suggestWrap.hide();}//发送请求,根据关键字到后台查询var sendKeyWord = function(event){//键盘选择下拉项if(suggestWrap.css('display')=='block'&&event.keyCode == 38||event.keyCode == 40){var current = suggestWrap.find('li.hover');if(event.keyCode == 38){if(current.length>0){if(current.length>0){var prevLi = current.removeClass('hover').prev();if(prevLi.length>0){prevLi.addClass('hover');input.val(prevLi.html());}}else{var last = suggestWrap.find('li:last');last.addClass('hover');input.val(last.html());}}else if(event.keyCode == 40){if(current.length>0){var nextLi = current.removeClass('hover').next();if(nextLi.length>0){nextLi.addClass('hover');input.val(nextLi.html());}}else{var first = suggestWrap.find('li:first');first.addClass('hover');input.val(first.html());}}//输⼊字符}else{var valText = $.trim(input.val());if(valText ==''||valText==key){return;}searchFuc(valText);key = valText;}}//请求返回后,执⾏数据展⽰this.dataDisplay = function(data){if(data.length<=0){suggestWrap.hide();return;}//往搜索框下拉建议显⽰栏中添加条⽬并显⽰var li;var tmpFrag = document.createDocumentFragment(); suggestWrap.find('ul').html('');for(var i=0; i<data.length; i++){li = document.createElement('LI');li.innerHTML = data[i];tmpFrag.appendChild(li);}suggestWrap.find('ul').append(tmpFrag);suggestWrap.show();//为下拉选项绑定⿏标事件suggestWrap.find('li').hover(function(){suggestWrap.find('li').removeClass('hover');$(this).addClass('hover');},function(){$(this).removeClass('hover');}).bind('click',function(){input.val(this.innerHTML);suggestWrap.hide();index.css。
使用jQuery模拟Google的自动提示效果
使用jQuery模拟Google的自动提示效果注意:1、本功能使用SqlServler2000中的示例数据库Northwind,请打SP3或SP4补丁;2、请下载jQuery组件,河西FTP中有下载;3、本功能实现类似Google自动提示的效果,通过ajax引擎从服务器获取,返回XML数据;4、本示例程序没考虑性能问题;5、不支持Firefox浏览器,因为该浏览器没有propertychange事件。
步骤:1、创建一个名为GoogleServlet的Servlet,负责从数据库中读取数据并生成XML格式的数据。
package com.aptech.servlet;import java.io.IOException;import java.io.PrintWriter;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class GoogleServlet extends HttpServlet {public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/xml;charset=utf-8");request.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();String key = request.getParameter("key");try {Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");Connection conn =DriverManager.getConnection("jdbc:sqlserver://127.0.0.1:1433;DatabaseName= northwind", "sa", "");PreparedStatement pstmt = conn.prepareStatement("select shipname,count(shipname) as c from [orders] where shipname like ? group by shipname");pstmt.setString(1, key + "%");ResultSet rs = pstmt.executeQuery();StringBuilder xml = new StringBuilder();xml.append("<results>");if(rs != null){while(rs.next()){xml.append("<result key=""" + rs.getString(1) + """ count=""" + rs.getInt(2) + """></result>");}}xml.append("</results>");rs.close();pstmt.close();conn.close();out.print(xml.toString());} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}out.flush();out.close();}}2、定义一个名为google.html的HTML文件,负责动态生成自动提示的效果。
(实现类似GOOGLE搜索框的自动提示功能+)AJAXTOOLKITAUTOCOMPLETEEXTENDER+用法详解
2. AutoCompleteExtender 的效果(功能)
如下图所示, 当在文本框中录入1 时, 所有包括1 的串都被显示出来, 当录入123 的时候, 包括123 的串被显示出来, 在这个下拉列表中单击选 中某一项, 则文本框的值改变为选中的项的值. (当选中某项时需要触发事件, 或想使用键值对的话, 请参阅我的另一篇文章ajaxToolkit:AutoCompleteExtender 的触发选择事件以及JSON序列化和使用键值对. 值得注意的是: 下拉列表中的项与文本框中录入的内容的关联的规则是自己定义的, 例如, 示例图中, 录入1时, 凡是包括1的串都被显示了出来, 无论1 在这个串的什么位置都可以, 但是可能你希望只显示以1 开头的串, 你只需要修改一下服务方法的实现即可, 稍eteExtender
既然名为Extender, 就说明它是一个扩展控件, 它必须依赖于别人而存在-----这个别人指的是文本框. 所以,
首先要有一个宿主文本框:
<asp:TextBox ID=&uot;txt1&uot; runat=&uot;server&uot;></asp:Tex
指令即可. 例如, 我的示例页面的指令:
<%@ Register Assembly=&uot;AjaxControlToolkit&uot; Namespace=&uot;AjaxControlToolkit&uot;
TagPrefix=&uot;ajaxToolkit&uot; %>
并不多, 于是我有了充分的理由再写一篇关于这个控件的详细介绍.
jquery 搜索框提示功能(完整版)
<%@ page language="java" pageEncoding="utf-8" contentType="text/html; charset=utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>jquery</title><style type="text/css">.searchTableTr{ background-color : gray;}.divSearchInput{display: none;position: absolute;border-width: 1px;overflow:hidden;background:none repeat scroll 0 0 #FFFFFF;border:#c5dadb 1px solid;}</style></head><body><div id="divSearchPage"><div id="divWidthAuto" style="border:#c5dadb 1px solid;border-width: 1px;height:30px;float: left;"><input type="text" name="search" id="search" style="border: 0px;height:30px;font-size: 16px;line-height: 30px;color: #000000;"></div> <input type="button" value="搜索" style="height:30;width:100"><input type="hidden" name="searchIndex" id="searchIndex" value="0"><input type="hidden" name="maxIndex" id="maxIndex" value="0"><div id="searhInput" class="divSearchInput" ><table id="searhTable"><tbody></tbody></table></div></div><script src="jquery.js"></script><script>//鼠标停留改变搜索显示的背景颜色functionchangeColor(v,i) {if ($("#searchIndex").val() != '') {var index = $("#searchIndex").val();if (index == 10) {index = 1;}$("#searhTabletr").each(function(i,v) {if (i == (index-1)) {$(this).removeClass();}})}$(v).addClass("searchTableTr");$(v).css("cursor","default");$("#searchIndex").val(i+1);}//鼠标离开移除搜索显示的背景颜色functionmoverColor(v) {$(v).removeClass();$(v).css("cursor","");$("#searchIndex").val(0);}//点击搜索显示信息functionsearchValue(v) {$("#search").val($(v).text());$("#searhInput").hide();}$(function(){$("#divWidthAuto").width(533);$("#search").width(530);$("#searhInput").width(533);$("#searhTable").width(533);vardisp = true;//点击空白处隐藏$(document).click(function(){//点击搜索处显示$("#divSearchPage").click(function(){disp = false;if ($('#searhInput').css('display') == 'block') {$('#searhInput').show();}});if (disp) {$('#searhInput').hide();}disp = true;});//右键点击搜索处显示$("#divSearchPage").bind("contextmenu",function(e){ $('#searhInput').show();});//输入框键盘触发事件$("#search").keyup(function(e){var key = e.which;//下键if(key == 40){$('#searhInput').show();var index = $("#searchIndex").val();varmaxIndex = $("#maxIndex").val();if (index == new Number(maxIndex)) {index = 0;}if (index == (new Number(maxIndex)+1)) {index = 1;}$("#searhTabletr").each(function(i,v) { if (i == index) {$("#search").val($(this).text());$(this).addClass("searchTableTr");} else {$(this).removeClass();}})index++;$("#searchIndex").val(index);}//上键if(key == 38){$('#searhInput').show();var index = $("#searchIndex").val();varmaxIndex = $("#maxIndex").val();if (index == 0) {index = (new Number(maxIndex)+1);}if (index == 1) {index = (new Number(maxIndex)+1);}index = index - 2;$("#searhTabletr").each(function(i,v) {if (i == index) {$("#search").val($(this).text());$(this).addClass("searchTableTr");} else {$(this).removeClass();}})index = index+1;$("#searchIndex").val(index);}if (key != 40 && key != 38) {if(this.value != '') {querySearchInfo(this);} else {$('#searhTable').empty();$('#searhInput').hide();}}});//搜索框输入functionquerySearchInfo(v) {jQuery.post("json.action",{value : $("#search").val()},function(json) {$("#searhTable").empty();$("#searhInput").hide();$("#searchIndex").val(0);for (i = 0;i <json.test.length;i++) {if (i == 10) {break;}$("#searhTable").append("<tronmousemove='changeColor(this,"+i+")'onmouseout='moverColor(this)' id='searchTr"+i+"'><td onclick='searchValue(this)'>"+json.test[i].a1+"</td></tr>")}if (json.test.length != 0) {var y = ($(v).offset().top+30);var x = ($(v).offset().left-1);$("#searhInput").css("top",y);$("#searhInput").css("left", x);varmaxIndex = json.test.length;if (json.test.length> 10) {maxIndex = 10;}$("#maxIndex").val(maxIndex);$("#searhInput").show();}},"json");}});</script></body></html>。
仿百度搜索智能提示(纯JS实现)
仿百度搜索智能提示(纯JS实现)项目中经常用到搜索智能提示,开源的象jQuery、yui等都有,但是觉得有点臃肿,于是自己用ajaxpro+JavaScript搞了一个目前只支持ie,可能还有若干个bug。
相信新手应该用得着吧,老鸟就算了。
大家发现了请指出,我马上改正,大家多多支持哈~~核心代码如下:代码var arrList = new Array();//要搜索的数据var objouter, objInput, objInputId = "txtSearch";//控件IDvar selectedIndex = -1, intTmp;//初始化function smanPromptList() {this.style ="overflow:hidden;width:393px;height:auto;background:#FFFFFF;border:1px solid #000000;font-size:14px;cursor:default;"if (arrList.constructor != Array) {alert('smanPromptList初始化失败:第一个参数非数组!');return;}document.write("<div id='__smanDisp'style='position:absolute;display:none;" + this.style + "'onblur></div>");document.write("<style type=\"text/css\">.sman_selectedStyle{background-Color:#3366CC;color:#FFFFFF}</style>");arrList.sort(function(a, b) {if (a.length > b.length) return 1;else if (a.length == b.length) return a.localeCompare(b);else return -1;});objouter = document.getElementById("__smanDisp") //显示的DIV对象objInput = document.getElementById(objInputId); //文本框对象if (objInput == null) {alert('smanPromptList初始化失败:没有找到"' + objInputId + '"文本框'); return;}objInput.onblur = function() { objouter.style.display = 'none'; } objInput.onkeyup = checkKeyCode;objInput.onfocus = checkAndShow;}function getAbsoluteHeight(ob) {return ob.offsetHeight;}function getAbsoluteWidth(ob) {return ob.offsetWidth;}function getAbsoluteLeft(ob) {var s_el = 0, el = ob;while (el) {s_el = s_el + el.offsetLeft;el = el.offsetParent;};return s_el;}function getAbsoluteTop(ob) {var s_el = 0, el = ob;while (el) {s_el = s_el + el.offsetTop;el = el.offsetParent;};return s_el;}function outSelection(Index) {objInput.value = objouter.children[Index].innerText.Trim();objouter.style.display = 'none';}function divPosition() {objouter.style.top = getAbsoluteHeight(objInput) +getAbsoluteTop(objInput);objouter.style.left = getAbsoluteLeft(objInput);objouter.style.width = getAbsoluteWidth(objInput);}function chageSelection(isUp) {if (objouter.style.display == 'none') {objouter.style.display = '';}else {if (isUp)selectedIndex++;elseselectedIndex--;}var maxIndex = objouter.children.length - 1;if (selectedIndex < 0) { selectedIndex = 0; }if (selectedIndex > maxIndex) { selectedIndex = maxIndex; }if (selectedIndex == maxIndex) { selectedIndex = -1; }for (intTmp = 0; intTmp <= maxIndex; intTmp++) {if (intTmp == selectedIndex) {objouter.children[intTmp].className = "sman_selectedStyle"; objInput.value = objouter.children[selectedIndex].innerText.Trim(); }else {objouter.children[intTmp].className = "";}}}function checkKeyCode() {var ie = (document.all) ? true : falseif (ie) {var keyCode = event.keyCodeif (keyCode == 40 || keyCode == 38) {var isUp = falseif (keyCode == 40)isUp = true;chageSelection(isUp)}else if (keyCode == 13) {outSelection(selectedIndex);}else {checkAndShow();}}else {checkAndShow();}divPosition();}function checkAndShow() {var strInput = objInput.value.Trim();if (strInput != "") {divPosition();selectedIndex = -1;arrList.length = 0;objouter.innerHTML = "";//=======================这里修改数据================================ var result = WebApplicationTestDiv.WebForm11.GetArray(strInput).value; //=================================================================== var data = eval('(' + result + ')');for (var j = 0; j < data.length; j++) {arrList[j] = data[j];}for (intTmp = 0; intTmp < arrList.length; intTmp++) {for (i = 0; i < arrList[intTmp].length; i++) {if (arrList[intTmp].substr(i, strInput.length).toUpperCase() == strInput.toUpperCase()) {addOption(arrList[intTmp], strInput);}if (objouter.childNodes.length >= 10) {break;}}}if (objouter.childNodes.length > 0) {objouter.innerHTML += "<div style=\"width:395px;height:22px;text-align:right;color:Blue;text- decoration:underline;cursor:pointer;\">关闭</div>";}objouter.style.display = '';}else {objouter.style.display = 'none';}}//显示搜索的数据并关键字涂色function addOption(value, keyw) {var v = value.replace(keyw, "<b><font color=\"red\">" + keyw +"</font></b>");objouter.innerHTML += "<div style=\"width:395px;height:22px\" onmouseover=\"this.className='sman_selectedStyle'\"onmouseout=\"this.className=''\"onmousedown=\"document.getElementById('" + objInputId + "').value='" + value + "'\">" + v + "</div>"}String.prototype.Trim = function() {return this.replace(/(^\s*)|(\s*$)/g, "");}smanPromptList();后台核心代码:代码[AjaxPro.AjaxMethod]public string GetArray(string name){try{List<string> list = new List<string>();#regionlist.Add("1");list.Add("12");list.Add("123");list.Add("1234");list.Add("12345");list.Add("123456");list.Add("1234567");list.Add("12345678");list.Add("123456789");list.Add("9876543210");list.Add("987654321");list.Add("98765432");list.Add("9876543");list.Add("987654");list.Add("98765");list.Add("9876");list.Add("987");list.Add("98");list.Add("9");list.Add("1111222");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("");list.Add("杨澜");list.Add("杨扬");list.Add("杨白劳");list.Add("杨钰莹");list.Add("杨百万");list.Add("杨一洋");list.Add("杨丞琳");list.Add("杨一尔");list.Add("杨二尔");#endregionList<string> l1 = list.FindAll(delegate(string ss) { return ss.Contains(name); });string str = "[";foreach (string s in l1){str += "\"" + s + "\"" + ","; }str = str.TrimEnd(',') + "]"; return str;}catch (Exception ex){throw ex;}}最后效果如图:。
jquery php 百度搜索框智能提示效果
jquery php 百度搜索框智能提示效果这个程序是利用php+ajax+jquery 实现的一个仿baidu智能提示的效果,有需要的朋友可以下载测试哦。
先来看看效果\代码如下index.html文件,保保存成index.htm代码如下复制代码<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Ajax Auto Suggest</title><script type="text/网页特效" src="jquery-1.2.1.pack.js"></script><script type="text/javascript">function lookup(inputString) {if(inputString.length == 0) {// Hide the suggestion box.$('#suggestions').hide();} else {$.post("rpc.php", {queryString: ""+inputString+""}, function(data){if(data.length >0) {$('#suggestions').show();$('#autoSuggestionsList').html(data);}});}} // lookupfunction fill(thisValue) {$('#inputString').val(thisValue);setTimeout("$('#suggestions').hide();", 200);}</script><style type="text/css教程"> body {font-family: Helvetica;font-size: 11px;color: #000;}h3 {margin: 0px;padding: 0px;}.suggestionsBox { position: relative;left: 30px;margin: 10px 0px 0px 0px; width: 200px; background-color: #212427; -moz-border-radius: 7px;-webkit-border-radius: 7px; border: 2px solid #000; color: #fff;}.suggestionList {margin: 0px;padding: 0px;}.suggestionList li {margin: 0px 0px 3px 0px; padding: 3px;cursor: pointer;}.suggestionList li:hover { background-color: #659CD8; }</style></head><body><div><form><div>Type your county:<br /><input type="text" size="30" value="" id="inputString" onkeyup="lookup(this.value);" onblur="fill();" /></div><div class="suggestionsBox" id="suggestions" style="display: none;"><img src="upArrow.png" style="position: relative; top: -12px; left: 30px;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div></div></form></div></body></html>php文件代码如下复制代码<?phpmysql教程_connect('localhost', 'root' ,'root');mysql_select_db("autoComplete");$queryString = $_POST['queryString'];if(strlen($queryString) >0) {$sql= "SELECT value FROM countries WHERE value LIKE '".$queryString."%' LIMIT 10";$query = mysql_query($sql);while ($result = mysql_fetch_array($query,MYSQL_BOTH)){$value=$result['value'];echo '<li onClick="fill(''.$value.'');">'.$value.'</li>';}}sql.sql把这里复制保存到你的数据库教程代码如下复制代码-- phpMyAdmin SQL Dump-- version 3.3.5-- ---- 主机: localhost-- 生成日期: 2010 年12 月09 日02:36-- 服务器版本: 5.0.22-- PHP 版本: 5.2.14SET SQL_MODE="NO_AUTO_V ALUE_ON_ZERO";/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */;---- 数据库: `autoComplete`---- ------------------------------------------------------------ 表的结构`countries`--CREATE TABLE IF NOT EXISTS `countries` (`id` int(6) NOT NULL auto_increment,`value` har(250) NOT NULL default '',PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=243 ;---- 转存表中的数据`countries`--INSERT INTO `countries` (`id`, `value`) V ALUES(1, 'Afghanistan'),(3, 'Albania'),(4, 'Algeria'),(5, 'American Samoa'),(6, 'Andorra'),(7, 'Angola'),(8, 'Anguilla'),(9, 'Antarctica'),(10, 'Antigua and Barbuda'), (11, 'Argentina'),(12, 'Armenia'),(13, 'Aruba'),(14, 'Australia'),(15, 'Austria'),(16, 'Azerbaijan'),(17, 'Bahamas'),(18, 'Bahrain'),(19, 'Bangladesh'),(20, 'Barbados'),(21, 'Belarus'),(22, 'Belgium'),(23, 'Belize'),(24, 'Benin'),(25, 'Bermuda'),(26, 'Bhutan'),(27, 'Bolivia'),(28, 'Bosnia and Herzegovina'), (29, 'Botswana'),(30, 'Bouvet Island'),(31, 'Brazil'),(32, 'British Indian Ocean territory'), (33, 'Brunei Darussalam'),(34, 'Bulgaria'),(35, 'Burkina Faso'),(36, 'Burundi'),(37, 'Cambodia'),(38, 'Cameroon'),(39, 'Canada'),(40, 'Cape Verde'),(41, 'Cayman Islands'),(42, 'Central African Republic'), (43, 'Chad'),(44, 'Chile'),(45, 'China'),(47, 'Cocos (Keeling) Islands'), (48, 'Colombia'),(49, 'Comoros'),(50, 'Congo'),(51, 'Congo'),(52, ' Democratic Republic'), (53, 'Cook Islands'),(54, 'Costa Rica'),(55, 'Ivory Coast (Ivory Coast)'), (56, 'Croatia (Hrvatska)'), (57, 'Cuba'),(58, 'Cyprus'),(59, 'Czech Republic'),(60, 'Denmark'),(61, 'Djibouti'),(62, 'Dominica'),(63, 'Dominican Republic'), (64, 'East Timor'),(65, 'Ecuador'),(66, 'Egypt'),(67, 'El Salvador'),(68, 'Equatorial Guinea'),(69, 'Eritrea'),(70, 'Estonia'),(71, 'Ethiopia'),(72, 'Falkland Islands'),(73, 'Faroe Islands'),(74, 'Fiji'),(75, 'Finland'),(76, 'France'),(77, 'French Guiana'),(78, 'French Polynesia'),(79, 'French Southern Territories'), (80, 'Gabon'),(81, 'Gambia'),(82, 'Georgia'),(83, 'Germany'),(84, 'Ghana'),(85, 'Gibraltar'),(86, 'Greece'),(87, 'Greenland'),(88, 'Grenada'),(89, 'Guadeloupe'),(91, 'Guatemala'),(92, 'Guinea'),(93, 'Guinea-Bissau'),(94, 'Guyana'),(95, 'Haiti'),(96, 'Heard and McDonald Islands'), (97, 'Honduras'),(98, 'Hong Kong'),(99, 'Hungary'),(100, 'Iceland'),(101, 'India'),(102, 'Indonesia'),(103, 'Iran'),(104, 'Iraq'),(105, 'Ireland'),(106, 'Israel'),(107, 'Italy'),(108, 'Jamaica'),(109, 'Japan'),(110, 'Jordan'),(111, 'Kazakhstan'),(112, 'Kenya'),(113, 'Kiribati'),(114, 'Korea (north)'),(115, 'Korea (south)'),(116, 'Kuwait'),(117, 'Kyrgyzstan'),(118, 'Lao People''s Democratic Republic'), (119, 'Latvia'),(120, 'Lebanon'),(121, 'Lesotho'),(122, 'Liberia'),(123, 'Libyan Arab Jamahiriya'),(124, 'Liechtenstein'),(125, 'Lithuania'),(126, 'Luxembourg'),(127, 'Macao'),(128, 'Macedonia'),(129, 'Madagascar'),(130, 'Malawi'),(131, 'Malaysia'),(132, 'Maldives'),(133, 'Mali'),(135, 'Marshall Islands'), (136, 'Martinique'),(137, 'Mauritania'),(138, 'Mauritius'),(139, 'Mayotte'),(140, 'Mexico'),(141, 'Micronesia'),(142, 'Moldova'),(143, 'Monaco'),(144, 'Mongolia'),(145, 'Montserrat'),(146, 'Morocco'),(147, 'Mozambique'),(148, 'Myanmar'),(149, 'Namibia'),(150, 'Nauru'),(151, 'Nepal'),(152, 'Netherlands'),(153, 'Netherlands Antilles'), (154, 'New Caledonia'), (155, 'New Zealand'),(156, 'Nicaragua'),(157, 'Niger'),(158, 'Nigeria'),(159, 'Niue'),(160, 'Norfolk Island'),(161, 'Northern Mariana Islands'), (162, 'Norway'),(163, 'Oman'),(164, 'Pakistan'),(165, 'Palau'),(166, 'Palestinian Territories'), (167, 'Panama'),(168, 'Papua New Guinea'), (169, 'Paraguay'),(170, 'Peru'),(171, 'Philippines'),(172, 'Pitcairn'),(173, 'Poland'),(174, 'Portugal'),(175, 'Puerto Rico'),(176, 'Qatar'),(177, 'Runion'),(179, 'Russian Federation'),(180, 'Rwanda'),(181, 'Saint Helena'),(182, 'Saint Kitts and Nevis'),(183, 'Saint Lucia'),(184, 'Saint Pierre and Miquelon'),(185, 'Saint Vincent and the Grenadines'),(186, 'Samoa'),(187, 'San Marino'),(188, 'Sao Tome and Principe'),(189, 'Saudi Arabia'),(190, 'Senegal'),(191, 'Serbia and Montenegro'),(192, 'Seychelles'),(193, 'Sierra Leone'),(194, 'Singapore'),(195, 'Slovakia'),(196, 'Slovenia'),(197, 'Solomon Islands'),(198, 'Somalia'),(199, 'South Africa'),(200, 'South Georgia and the South Sandwich Islands'), (201, 'Spain'),(202, 'Sri Lanka'),(203, 'Sudan'),(204, 'Suriname'),(205, 'Svalbard and Jan Mayen Islands'),(206, 'Swaziland'),(207, 'Sweden'),(208, 'Switzerland'),(209, 'Syria'),(210, 'Taiwan'),(211, 'Tajikistan'),(212, 'Tanzania'),(213, 'Thailand'),(214, 'Togo'),(215, 'Tokelau'),(216, 'Tonga'),(217, 'Trinidad and Tobago'),(218, 'Tunisia'),(219, 'Turkey'),(220, 'Turkmenistan'),(221, 'Turks and Caicos Islands'),(223, 'Uganda'),(224, 'Ukraine'),(225, 'United Arab Emirates'), (226, 'United Kingdom'), (227, 'United States of America'), (228, 'Uruguay'),(229, 'Uzbekistan'),(230, 'Vanuatu'),(231, 'Vatican City'),(232, 'Venezuela'),(233, 'Vietnam'),(234, 'Virgin Islands (British)'), (235, 'Virgin Islands (US)'), (236, 'Wallis and Futuna Islands'), (237, 'Western Sahara'), (238, 'Yemen'),(239, 'Zaire'),(240, 'Zambia'),(241, 'Zimbabwe');。
JSP+Ajax仿Google百度搜索提示
JSP+[Servlet]+Ajax模仿Google和百度搜索的自动提示练习:前几天想练习下,找个实例做做,无奈百度之后并没有非常完整详细的的或者的模仿搜索网站的实例。
于是自己参考了各种资料自己完成了一个,将表单和和代码全部写在了一个页面中并且写了非常详细的注释。
希望和我一样想练习同学可以参考和学习。
以后还会使用实现,此处只是作为的综合练习。
比较遗憾的是详细的开发过程不能展示给大家了,但是这样可以锻炼大家阅读代码的能力,我在没有注释的情况下参考资料写了详细的注释,还是有点成就感的,感觉最大的收获就是阅读代码的能力上升了不少,建议大家也多读读别人的代码。
下面先上效果图:如果想要做这个需要以下基础:·语言·语言(重点应用)·技术·(或者其他类似语言、等等)·一点点数据库先看看实现以上效果,我的工程目录使用数据库·:取得数据库连接,关闭连接;·:提交到此主要是取得提示数据·:主要视窗,即上图界面·:表单提交之后跳转的页面·数据库:是全国省市县的所有信息(包含脚本、脚本、、)整个工程都会给出下载地址:百度网盘:云诺网盘:下面是各个文件的详细内容:注释很清楚不再赘述数据库连接类:如果你不是使用数据库,你可以自己写一个数据库连接类。
脚本在下载的包里面都有数据库连接类获取连接关闭连接主页面的综合体(难度最大,但是最详细)示例记录当前列表被选中的编号获取对象、、等测试之用有反应获取按键的代号通过测试和都是调用这句调用这句核心方法,获取数据库数据是,是,是是对字符串进行编码,转化为进制数据,类似中的如果没有输入内容或者输入的内容是空的,则不现实任何东西规定请求的类型、以及是否异步处理请求。
:请求的类型;或:文件在服务器上的位置:(异步)或(同步)将请求发送到服务器。
:仅用于请求取得对象设置回调函数如果一切正常就执行一下代码为设置内容调用;创建一条请求发送创建的请求设置为可见为设置样式,设置选中高亮获得所有的标签遍历所有的标签,找到指定的编号的标签找到指定的标签,为其设置样式并且选择到该项的时候为搜索框设置该项的值如果没有找到,啥都不做按和键时的操作(键盘选择)得到按键代号获取节点对象如果没有选项,直接返回如果是按的键将加如果已经到达最底部,则回到第一项如果按的是键如果到达最顶端,则返回到最后一项将选中项的值设置到文本框中为选定的项设置样式鼠标经过时的操作,此处的在中传入鼠标离开时的操作当鼠标离开之后上没有样式此处定义函数模仿,根据获取属性获取指定节点的位置找到指定的位置的坐标上、下、左、右找到一个元素位置(一般为)作为坐标的原点设置为指定的元素设置位置此处为节点对象比如:调用传入方法内,例如:此处需要将的设置:才能有效将的位置设置左边与对齐将的位置设置在的下方提交之后的事件提交该页面中的第一个表单若点击某项,将某项的值设置到搜索框中并提交表单为设置值提交表单谷歌搜索接下来是(大家应该会配置吧就不贴了)此处的语句是用的,其中用到了分页,其他的数据库记得更改这一条语句配合使用的,查询数据用获取提交的值取得数据库连接存放隐藏中的代码为每个指定一个编号此句为核心获取数据出错无论如何都要关闭各个连接输出代码最后是这个可以不看提交过来的数据至此运行下应该就可以得到上图的效果了,和百度的非常类似哦。
如何利用搜索引擎的智能提示功能
如何利用搜索引擎的智能提示功能在当今信息爆炸的时代,搜索引擎已经成为我们获取知识和解决问题的重要工具。
而搜索引擎的智能提示功能,更是为我们的搜索体验带来了极大的便利。
那么,如何充分利用这一功能,让我们的搜索更加高效和精准呢?首先,我们要了解搜索引擎智能提示功能的工作原理。
简单来说,它是基于用户的搜索历史、热门搜索趋势以及相关的关键词联想等因素来提供提示的。
当我们在搜索框中输入几个字符时,搜索引擎会迅速预测我们可能想要搜索的内容,并给出一系列相关的提示选项。
在使用智能提示功能时,要善于输入简洁而具有代表性的关键词。
比如说,如果您想了解某个城市的旅游景点,不要一开始就输入很长的句子,而是先输入城市的名称,如“北京”,这时搜索引擎很可能会给出“北京旅游景点”“北京美食”“北京天气”等相关的提示。
从这些提示中,您可以快速找到最符合您需求的选项,从而节省输入完整关键词的时间。
另外,要灵活运用模糊搜索和精确搜索。
有时候,我们可能对要搜索的内容并不是非常明确,这时候可以使用一些比较模糊的关键词,让智能提示功能为我们提供更多的思路和可能性。
例如,输入“健康”,可能会出现“健康饮食”“健康生活方式”“健康运动”等提示。
而当我们对搜索内容有比较明确的目标时,则要输入更精确的关键词,以获得更准确的提示。
比如,“健康饮食的食谱”,搜索引擎可能会给出“健康饮食的早餐食谱”“健康饮食的减肥食谱”等更有针对性的提示。
同时,注意观察智能提示中的热门搜索选项。
这些热门搜索往往反映了当前大家普遍关注的话题和需求。
如果您的搜索需求与这些热门话题相关,不妨从热门提示中选择,这样可能会获取到更丰富和最新的信息。
除了以上提到的方法,我们还可以利用智能提示功能来拓展搜索思路。
比如说,您原本想搜索“如何学习英语语法”,但在输入“如何学习”时,看到智能提示中的“如何学习编程”“如何学习绘画”等选项,也许会突然启发您思考其他学习领域的方法和技巧,从而拓宽了您的知识视野。
利用jsonp跨域调用百度js实现搜索框智能提示
利⽤jsonp跨域调⽤百度js实现搜索框智能提⽰项⽬中常常⽤到搜索,特别是导航类的⽹站。
⾃⼰做关键字搜索不太现实,直接调⽤百度的是最好的选择。
使⽤jquery.ajax的jsonp⽅法可以异域调⽤到百度的js并拿到返回值,当然$.getScript也可以实现跨域调⽤js。
ok,了解了jsonp的原理和应⽤后,我们看看百度的智能提⽰是如何做的在chrome的调试窗⼝下看看百度搜索发出的请求。
当输⼊关键字“a”,请求如图:⽤firebug看下请求的参数,如图:请求⽅式:get请求请求参数:wd明显是要搜索的关键字;cb是请求回来的处理函数,名字可以随便给;t是时间戳,防⽌缓存的;p不知道什么意思,每次请求都给3就可以了;sid也不知道什么意思,不要也可以请求,如果想要也可以带上,值就是上⾯截图的值。
请求地址和参数都知道了,于是写下如下js测试是否可以拿到关键字提⽰(源码⾥的test.html页⾯):var qsData = { 'wd': ‘a', 'p': '3', 'cb': 'getData', 't': new Date().getMilliseconds().toString() };$.ajax({async: false,url: "/su",type: "GET",dataType: 'jsonp',jsonp: 'jsoncallback',data: qsData,timeout: 5000,success: function (json) {},error: function (xhr) {}});qsData封装所有请求要发送的参数;getData是⾃定义的名称,⽤于处理返回的关键字(以下⽰例代码把请求回来的关键字打印到了FireBug的控制台):function getData(data) {var Info = data['s']; //获取异步数据console.log(Info);}监控下⽂本框,实时的发送ajax请求并拿回数据是这样的:ok,测试可⽤,的确可以拿到关键字提⽰。
jquery+php实现用户输入搜索内容时自动提示
jquery+php实现用户输入搜索内容时自动提示时间:2011-01-13 16:35 来源:PHP100中文网作者:PHP100er 点击: 3242 次【字号:大中小】今天突然想给本站做个搜索页面,这样用户可以通过搜索来找到自己喜欢的内容,也避免了在海量信息中手动查找资源的麻烦,我的目标和百度首页的效果类似,当用户输入要搜索的文字时,我们在下方给出相关的十条信息,如果用户要找的就是这十条信息内的某一条,今天突然想给本站做个搜索页面,这样用户可以通过搜索来找到自己喜欢的内容,也避免了在海量信息中手动查找资源的麻烦,我的目标和百度首页的效果类似,当用户输入要搜索的文字时,我们在下方给出相关的十条信息,如果用户要找的就是这十条信息内的某一条,那么简单,直接点击就可在新页面中打开页面,主要就是想更人性化一点,让用户使用起来更方便。
先看一下效果图吧,这样更有动力,要不然大家还不知道我在讲什么,到底要达到什么样的效果!下面先主要讲解原理:在search.html页面中,用户在搜索框内输入“j”时,使用javascript获取搜索框的文本内容,到数据库中查找相关的内容并返回,再使用javascript将服务器返回的结果显示在搜索框下面的提示框内,供用户参考选择。
具体的实现方法:首先在页面中做好搜索框、搜索按钮、显示搜索提示的层,如下代码<div id="search"><input type="text" name="k" class="k" /> <input type="button" name="s" value="搜索" /></div><div id="search_auto"></div>使用浏览器浏览页面,会看到下图的效果看起来很普通,没什么样式,现在稍作样式上的调整#search{font-size:14px;}#search .k{padding:2px 1px; width:320px;} /*将搜索框宽度设置大点*/再将显示搜索提示的层样式调整一下,由于搜索提示层在搜索框正下方,所以我们设置其定位方式为绝对定位#search_auto{border:1px solid #817FB2; position:absolute;} /*设置边框、定位方式*/接着用JS将搜索提示层的位置放置在搜索框正下方,且宽度和搜索框相同,这里我们采用jQuery来解决$('#search_auto').css({'width':$('#search input[name="k"]').width()+4});搜索提示层的位置和宽度已经确定好了,由于在用户没有输入搜索文字前这个提示框是不显示的,所以我们先要将它设置成隐藏,在提示层的样式里加上display:none将其隐藏。
jquery之仿百度搜索框
jquery之仿百度搜索框最近项⽬中⽤到类似百度的输⼊框,于是⾃⼰⽤jquery写了⼀个。
希望和⼤家共同分享⼀下。
存在许多bug,请各位不吝赐教。
先看看整个的效果图:图⼀:图⼆:图三:图四:⼤概的效果图就这样,接下来直接看源码页⾯:View Code1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="autoSearch._Default" %>23 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""/TR/xhtml1/DTD/xhtml1-transitional.dtd">45 <html xmlns="/1999/xhtml" >6 <head runat="server">7 <title></title>8 <link href="autoSearchText.css" type="text/css" rel="Stylesheet" />9 <script src="jquery-1.5.1.min.js" type="text/javascript"></script>10 <%if (false){ %>11 <script type="text/javascript" src="jquery-1.5.1.js"></script>12 <%} %>13 <script src="jquery.autoSearchText.js" type="text/javascript"></script>14 <script type="text/javascript">15 $(document).ready(function() {16 $('#autoSearchText').autoSearchText({ width: 300, itemHeight: 150,minChar:1, datafn: getData, fn: alertMsg });17 });18 function alertMsg(vl){19 alert('你将要搜索的关键字是: '+vl);20 }21/*加载数据*/22 function getData(val) {23 var arrData = new Array();24if (val != "") {25 $.ajax({26 type: "post",27 async: false, //控制同步28 url: "getData.ashx",29 data: "param=" + val,30 dataType: "json",31 cache: false,32 success: function(data) {33for (var i = 0; i < data.length; i++) {34if (val == data[i].Code.substring(0, val.length))35 arrData.push(data[i].Code);36 }37 },38 Error: function(err) {39 alert(err);40 }41 });42 }43return arrData;44 }45 </script>46 </head>47 <body>48 <form id="form1" runat="server">49 <div>50 <input id="autoSearchText" type="text" value="请输⼊编码" enableviewstate="false"/>51 <br />52 <input id="Text1" type="text" style=" display:none;"/>53 </div>54 </form>55 </body>56 </html>CSS:View Code1.autoSearchText{2 border:solid 1px #CFCFCF;3 height:20px;4 color:Gray;5 }6.menu_v{7 margin:0;8 padding:0;9 line-height:20px;10 font-size:12px;11 list-style-type:none;12 }13.menu_v li{14 margin:0;15 padding:0;16 line-height:20px;17 font-size:14px;18 list-style-type:none;19 float:none;20 }21.menu_v li span{22 color:Red;23 }24#autoSearchItem{25 border:solid 1px #CFCFCF;26 visibility:hidden;27 position:absolute;28 background-color:white;29 overflow-y:auto;30 }JS:View Code1///<reference path="jquery-1.5.1.js" />23 (function($) {4var itemIndex = 0;56 $.fn.autoSearchText = function(options) {7//以下为该插件的属性及其默认值8var deafult = {9 width: 200, //⽂本框宽10 itemHeight: 150, // 下拉框⾼11 minChar: 1, //最⼩字符数(从第⼏个开始搜索)12 datafn: null, //加载数据函数13 fn: null//选择项后触发的回调函数14 };15var textDefault = $(this).val();16var ops = $.extend(deafult, options);17 $(this).width(ops.width);18var autoSearchItem = '<div id="autoSearchItem"><ul class="menu_v"></ul></div>';19 $(this).after(autoSearchItem);2021 $('#autoSearchItem').width(ops.width + 2); //设置项宽22 $('#autoSearchItem').height(ops.itemHeight); //设置项⾼2324 $(this).focus(function() {25if ($(this).val() == textDefault) {26 $(this).val('');27 $(this).css('color', 'black');28 }29 });30var itemCount = $('li').length; //项个数31/*⿏标按下键时,显⽰下拉框,并且划过项时改变背景⾊及赋值给输⼊框*/32 $(this).bind('keyup', function(e) {33if ($(this).val().length >= ops.minChar) {34var position = $(this).position();35 $('#autoSearchItem').css({ 'visibility': 'visible', 'left': position.left, 'top': position.top + 24 }); 36var data = ops.datafn($(this).val());37 initItem($(this), data);38var itemCount = $('li').length;39switch (e.keyCode) {40case 38: //上41if (itemIndex > 1) {42 itemIndex--;43 }44 $('li:nth-child(' + itemIndex + ')').css({ 'background': 'blue', 'color': 'white' });45 $(this).val($('li:nth-child(' + itemIndex + ')').find('font').text());46break;47case 40: //下48if (itemIndex < itemCount) {49 itemIndex++;50 }51 $('li:nth-child(' + itemIndex + ')').css({ 'background': 'blue', 'color': 'white' });52 $(this).val($('li:nth-child(' + itemIndex + ')').find('font').text());53break;54case 13: //Enter55if (itemIndex > 0 && itemIndex <= itemCount) {56 $(this).val($('li:nth-child(' + itemIndex + ')').find('font').text());57 $('#autoSearchItem').css('visibility', 'hidden');58 ops.fn($(this).val());59 }60break;61default:62break;63 }64 }65 });66/*点击空⽩处隐藏下拉框*/67 $(document).click(function() {68 $('#autoSearchItem').css('visibility', 'hidden');69 });70 };71/*获取⽂本框的值*/72 $.fn.getValue = function() {73return $(this).val();74 };7576/*初始化下拉框数据,⿏标移过每项时,改变背景⾊并且将项的值赋值给输⼊框*/77function initItem(obj, data) {78var str = "";79if (data.length == 0) {80 $('#autoSearchItem ul').html('<div style="text-align:center;color:red;">⽆符合数据<div>');81 }82else {83for (var i = 1; i <= data.length; i++) {84 str += "<li><span>" + i + "/" + data.length + "</span>\r<font>" + data[i - 1] + "</font></li>";85 }86 $('#autoSearchItem ul').html(str);87 }88/*点击项时将值赋值给搜索⽂本框*/89 $('li').each(function() {90 $(this).bind('click', function() {91 obj.val($(this).find('font').text());92 $('#autoSearchItem').css('visibility', 'hidden');93 });94 });95/*⿏标划过每项时改变背景⾊*/96 $('li').each(function() {97 $(this).hover(98function() {99 $('li:nth-child(' + itemIndex + ')').css({ 'background': 'white', 'color': 'black' });100 itemIndex = $('li').index($(this)[0]) + 1;101 $(this).css({ 'background': 'blue', 'color': 'white' });102 obj.val($('li:nth-child(' + itemIndex + ')').find('font').text());103 },104function() {105 $(this).css({ 'background': 'white', 'color': 'black' });106 }107 );108 });109 };110 })(jQuery);getdata.ashxView Code1using System;2using System.Collections.Generic;3using System.Linq;4using System.Web;5using System.Web.Services;67namespace table8 {9///<summary>10/// $codebehindclassname$ 的摘要说明11///</summary>12 [WebService(Namespace = "/")]13 [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]14public class getData : IHttpHandler15 {1617public void ProcessRequest(HttpContext context)18 {19 context.Response.Clear();20string value = GetResult();21 context.Response.Write(value);22 context.Response.End();23 }2425private string GetResult()26 {27string result = string.Empty;2829 result = @"30 [{""id"":""1"",""Code"":""1374123""},31 {""id"":""2"",""Code"":""1374133""},32 {""id"":""3"",""Code"":""1374143""},33 {""id"":""4"",""Code"":""1374153""},34 {""id"":""5"",""Code"":""1374163""},35 {""id"":""6"",""Code"":""1374173""},36 {""id"":""7"",""Code"":""1374183""},37 {""id"":""8"",""Code"":""1374193""},38 {""id"":""9"",""Code"":""1374213""},39 {""id"":""10"",""Code"":""1374223""},40 {""id"":""11"",""Code"":""1374233""},41 {""id"":""12"",""Code"":""1374243""},42 {""id"":""13"",""Code"":""1374253""},43 {""id"":""14"",""Code"":""1374263""},44 {""id"":""15"",""Code"":""1374273""},45 {""id"":""16"",""Code"":""1374283""},46 {""id"":""17"",""Code"":""1374293""},47 {""id"":""18"",""Code"":""1374313""},48 {""id"":""19"",""Code"":""1374323""},49 {""id"":""20"",""Code"":""1374333""},50 {""id"":""21"",""Code"":""1374343""},51 {""id"":""22"",""Code"":""1374353""},52 {""id"":""23"",""Code"":""1374363""},53 {""id"":""24"",""Code"":""1374373""},54 {""id"":""25"",""Code"":""1374383""},55 {""id"":""26"",""Code"":""1374393""},56 {""id"":""27"",""Code"":""1374403""},57 {""id"":""28"",""Code"":""1374413""},58 {""id"":""29"",""Code"":""1374423""},59 {""id"":""30"",""Code"":""1374433""},60 {""id"":""31"",""Code"":""1374443""},61 {""id"":""32"",""Code"":""1374453""},62 {""id"":""33"",""Code"":""1374463""},63 {""id"":""34"",""Code"":""1374473""},64 {""id"":""35"",""Code"":""1374483""},65 {""id"":""36"",""Code"":""1374493""}]"; 6667return result;68 }6970public bool IsReusable71 {72get73 {74return false;75 }76 }77 }78 }。
搜索框输入文字自动提示
搜索框输⼊⽂字⾃动提⽰<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>搜索框输⼊⽂字⾃动提⽰</title><link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css"><style type="text/css">.container {padding-top: 150px;}.list-group {display: none;}</style></head><body><div class="container"><div class="form-group"><input type="text" class="form-control" placeholder="请输⼊搜索关键字" id="search"><ul class="list-group" id="list-box"></ul></div></div><script src="/js/ajax.js"></script><script src="/js/template-web.js"></script><script type="text/html" id="tpl">{{each result}}<li class="list-group-item">{{$value}}</li>{{/each}}</script><script>// 获取搜索框var searchInp = document.getElementById('search');// 获取提⽰⽂字的存放容器var listBox = document.getElementById('list-box');// 存储定时器的变量var timer = null;// 当⽤户在⽂本框中输⼊的时候触发searchInp.oninput = function () {// 清除上⼀次开启的定时器clearTimeout(timer);// 获取⽤户输⼊的内容var key = this.value;// 如果⽤户没有在搜索框中输⼊内容if (key.trim().length == 0) {// 将提⽰下拉框隐藏掉listBox.style.display = 'none';// 阻⽌程序向下执⾏return;}// 开启定时器让请求延迟发送timer = setTimeout(function () {// 向服务器端发送请求// 向服务器端索取和⽤户输⼊关键字相关的内容ajax({type: 'get',url: 'http://localhost:3000/searchAutoPrompt',data: {key: key},success: function (result) {// 使⽤模板引擎拼接字符串var html = template('tpl', {result: result});// 将拼接好的字符串显⽰在页⾯中 listBox.innerHTML = html;// 显⽰ul容器listBox.style.display = 'block';}})}, 800)}</script></body></html>。
jquery+ajax搜索提示的实现
jquery+ajax搜索提⽰的实现⼤概要实现的内容这是⼀个很简单的⽰例,服务器端只是⽤了⼀个jsp页⾯,返回的类型为xml。
先讲下是怎么回事,就是在浏览器端,通过ajax 请求,发送⼀串英⽂字母,服务器端通过⽐较,返回具有相同前缀的英⽂单词。
就这么个意思。
⼯程是在IntelliJ IDE中完成的。
做前端开发感觉⽤IntelliJ⽐较⽅便,因为对于写javascript的话,有函数名的提⽰。
本例提供下载。
望各位提出宝贵意见哈。
⼀、客户端JSP页⾯Html代码收藏代码<%--Created by IntelliJ IDEA.User: JayChangDate: 2010-11-22Time: 8:33:11To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>⾃动完成⽰例⼆、作为服务器端的JSP,返回的是XML这⾥稍作解释,为了⽅便起见,在服务器端只是很简单的处理,返回有相同前缀的英⽂单词。
没有对空格等复杂的搜索条件作处理,本例主要还是侧重于浏览器端的JavaScript。
Html代码收藏代码<%--Created by IntelliJ IDEA.User: JayChangDate: 2010-11-22Time: 8:33:22To change this template use File | Settings | File Templates.--%><%@page contentType="text/xml; charset=UTF-8"%><%String reqWord = request.getParameter("reqWord");System.out.println(reqWord);%><%if("absolute".startsWith(reqWord)){%> absolute<%}%><%if("air".startsWith(reqWord)){%>air<%}%><%if("apple".startsWith(reqWord)){%> apple<%}%><%if("amaze".startsWith(reqWord)){%> amaze<%}%><%if("bat".startsWith(reqWord)){%>bat<%}%><%if("bicycle".startsWith(reqWord)){%> bicycle<%}%><%if("bite".startsWith(reqWord)){%> bite<%}%><%if("bottle".startsWith(reqWord)){%> bottle<%}%><%if("cat".startsWith(reqWord)){%>cat<%}%><%if("carry".startsWith(reqWord)){%> carry<%}%><%if("castle".startsWith(reqWord)){%> castle<%}%>。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
完善了以下功能:1,中文传参,参数名称没有改动,仍是默认的q:String toPage = request.getParameter("q");page= new String(toPage.getBytes("ISO-8859-1"), "UTF-8");2,支持上下翻页,并且文本框的值即时改动,和google、百度一个效果3,鼠标事件,鼠标离开时层失去焦点,不锁定提示层4,已经匹配的字用细体显示,未匹配的用黑体显示,5,,增加提交之前的验证,比入输入中文时候需要敲空格,则输入之前不传参,还有一些细微的完善,此处不赘述,需注意的是,若需实现本人完善的效果,需要另存本人的jquery.autocomplete.js文件,以及jquery.autocomplete.css文件,另外几个文件,请到官网下载:http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/jquery.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""/TR/html4/loose.dtd"><html><head><script src="js/jquery-latest.js"></script><link rel="stylesheet" href="js/jquery.autocomplete.css" type="text/css" /><script type="text/javascript" src="js/jquery.bgiframe.min.js"></script><script type="text/javascript" src="js/jquery.dimensions.js"></script><script type="text/javascript" src="js/jquery.autocomplete.js"></script><script>$(document).ready(function(){$("#example").autocomplete("Jquery");});</script></head><body>API Reference: <input id="example" size=40/> (try "C" or "E")</body></html>jquery.autocomplete.js代码如下:/*** 此js为本人修改完善版,以下功能* ---李小朋2:45 2010-10-31**/;(function($) {$.fn.extend({autocomplete: function(urlOrData, options) {var isUrl = typeof urlOrData == "string";options = $.extend({}, $.Autocompleter.defaults, {url: isUrl ? urlOrData : null,data: isUrl ? null : urlOrData,delay: isUrl ? $.Autocompleter.defaults.delay : 10,max: options && !options.scroll ? 10 : 150}, options);// if highlight is set to false, replace it with a do-nothing functionoptions.highlight = options.highlight || function(value) { return value; };// if the formatMatch option is not specified, then use formatItem for backwards compatibility options.formatMatch = options.formatMatch || options.formatItem;return this.each(function() {new $.Autocompleter(this, options);});},result: function(handler) {return this.bind("result", handler);},search: function(handler) {return this.trigger("search", [handler]);},flushCache: function() {return this.trigger("flushCache");},setOptions: function(options){return this.trigger("setOptions", [options]);},unautocomplete: function() {return this.trigger("unautocomplete");}});$.Autocompleter = function(input, options) {var KEY = {UP: 38,DOWN: 40,DEL: 46,TAB: 9,RETURN: 13,ESC: 27,COMMA: 188,PAGEUP: 33,PAGEDOWN: 34,BACKSPACE: 8};// Create $ object for input elementvar $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);var timeout;var previousValue = "";var cache = $.Autocompleter.Cache(options);var hasFocus = 0;var lastKeyPressCode;var config = {mouseDownOnSelect: false};var select = $.Autocompleter.Select(options, input, selectCurrent, config);var blockSubmit;// prevent form submit in opera when selecting with return key$.browser.opera && $(input.form).bind("submit.autocomplete", function() {if (blockSubmit) {blockSubmit = false;return false;}});// only opera doesn't trigger keydown multiple times while pressed, others don't work withkeypress at all$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { // track last key pressedlastKeyPressCode = event.keyCode;switch(event.keyCode) {case KEY.UP:event.preventDefault();if ( select.visible() ) {select.prev();} else {onChange(0, true);}break;case KEY.DOWN:event.preventDefault();if ( select.visible() ) {select.next();} else {onChange(0, true);}break;case KEY.PAGEUP:event.preventDefault();if ( select.visible() ) {select.pageUp();} else {onChange(0, true);}break;case KEY.PAGEDOWN:event.preventDefault();if ( select.visible() ) {select.pageDown();} else {onChange(0, true);}break;// matches also semicoloncase options.multiple && $.trim(options.multipleSeparator) == "," && MA: case KEY.TAB:case KEY.RETURN:if( selectCurrent() ) {// stop default to prevent a form submit, Opera needs special handlingevent.preventDefault();blockSubmit = true;return false;}break;case KEY.ESC:select.hide();break;default:clearTimeout(timeout);timeout = setTimeout(onChange, options.delay);break;}}).focus(function(){// track whether the field has focus, we shouldn't process any// results if the field no longer has focushasFocus++;}).blur(function() {hasFocus = 0;if (!config.mouseDownOnSelect) {hideResults();}}).click(function() {// show select when clicking in a focused fieldif ( hasFocus++ > 1 && !select.visible() ) {onChange(0, true);}}).bind("search", function() {// TODO why not just specifying both arguments?var fn = (arguments.length > 1) ? arguments[1] : null;function findValueCallback(q, data) {var result;if( data && data.length ) {for (var i=0; i < data.length; i++) {if( data[i].result.toLowerCase() == q.toLowerCase() ) {result = data[i];break;}}}if( typeof fn == "function" ) fn(result);else $input.trigger("result", result && [result.data, result.value]);}$.each(trimWords($input.val()), function(i, value) {request(value, findValueCallback, findValueCallback);});}).bind("flushCache", function() {cache.flush();}).bind("setOptions", function() {$.extend(options, arguments[1]);// if we've updated the data, repopulateif ( "data" in arguments[1] )cache.populate();}).bind("unautocomplete", function() {select.unbind();$input.unbind();$(input.form).unbind(".autocomplete");});function selectCurrent() {var selected = select.selected();if( !selected )return false;var v = selected.result;previousValue = v;if ( options.multiple ) {var words = trimWords($input.val());if ( words.length > 1 ) {v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;}v += options.multipleSeparator;}$input.val(v);hideResultsNow();$input.trigger("result", [selected.data, selected.value]);}function onChange(crap, skipPrevCheck) {if( lastKeyPressCode == KEY.DEL ) {select.hide();return;}var currentValue = $input.val();if ( !skipPrevCheck && currentValue == previousValue ) return;previousValue = currentValue;currentValue = lastWord(currentValue);if ($.trim(currentValue).length >= options.minChars) { $input.addClass(options.loadingClass);if (!options.matchCase)currentValue = currentValue.toLowerCase(); request(currentValue, receiveData, hideResultsNow); } else {stopLoading();select.hide();}};function trimWords(value) {if ( !value ) {return [""];}var words = value.split( options.multipleSeparator ); var result = [];$.each(words, function(i, value) {if ( $.trim(value) )result[i] = $.trim(value);});return result;}function lastWord(value) {if ( !options.multiple )var words = trimWords(value);return words[words.length - 1];}// fills in the input box w/the first match (assumed to be the best match)// q: the term entered// sValue: the first matching resultfunction autoFill(q, sValue){// autofill in the complete box w/the first match as long as the user hasn't entered in more data// if the last user key pressed was backspace, don't autofillif( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {// fill in the value (keep the case the user has typed)$input.val($input.val() + sValue.substring(lastWord(previousValue).length));// select the portion of the value not typed by the user (so the next character will erase) $.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);}};function hideResults() {clearTimeout(timeout);timeout = setTimeout(hideResultsNow, 200);};function hideResultsNow() {var wasVisible = select.visible();select.hide();clearTimeout(timeout);stopLoading();if (options.mustMatch) {// call search and run callback$input.search(function (result){// if no value found, clear the input boxif( !result ) {if (options.multiple) {var words = trimWords($input.val()).slice(0, -1);$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );}else$input.val( "" );}});}if (wasVisible)// position cursor at end of input field$.Autocompleter.Selection(input, input.value.length, input.value.length); };function receiveData(q, data) {if ( data && data.length && hasFocus ) {stopLoading();select.display(data, q);autoFill(q, data[0].value);select.show();} else {hideResultsNow();}};function request(term, success, failure) {if (!options.matchCase)term = term.toLowerCase();var data = cache.load(term);// recieve the cached dataif (data && data.length) {success(term, data);// if an AJAX url has been supplied, try loading the data now} else if( (typeof options.url == "string") && (options.url.length > 0) ){var extraParams = {timestamp: +new Date()};$.each(options.extraParams, function(key, param) {extraParams[key] = typeof param == "function" ? param() : param; });$.ajax({// try to leverage ajaxQueue plugin to abort previous requestsmode: "abort",// limit abortion to this inputport: "autocomplete" + ,dataType: options.dataType,url: options.url,data: $.extend({q: lastWord(term),limit: options.max}, extraParams),success: function(data) {var parsed = options.parse && options.parse(data) || parse(data);cache.add(term, parsed);success(term, parsed);}});} else {// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful matchselect.emptyList();failure(term);}};function parse(data) {var parsed = [];var rows = data.split("&");for (var i=0; i < rows.length; i++) {var row = $.trim(rows[i]);if (row) {row = row.split("|");parsed[parsed.length] = {data: row,value: row[0],result: options.formatResult && options.formatResult(row, row[0]) || row[0]};}}return parsed;};function stopLoading() {$input.removeClass(options.loadingClass);};};$.Autocompleter.defaults = {inputClass: "ac_input",resultsClass: "ac_results",loadingClass: "ac_loading",minChars: 1,delay: 400,matchCase: false,matchSubset: true,matchContains: false,cacheLength: 10,max: 10,mustMatch: false,extraParams: {},selectFirst: false,formatItem: function(row) {return row[0]; },formatMatch: null,autoFill: false,width: 0,multiple: false,multipleSeparator: ", ",highlight: function(value, term) {return value.replace($.trim(term), "<span style='font-weight:Lighter;' >"+$.trim(term)+"</span>");},scroll: false,scrollHeight: 180};$.Autocompleter.Cache = function(options) {var data = {};var length = 0;function matchSubset(s, sub) {if (!options.matchCase)s = s.toLowerCase();var i = s.indexOf(sub);if (options.matchContains == "word"){i = s.toLowerCase().search("\\b" + sub.toLowerCase());}if (i == -1) return false;return i == 0 || options.matchContains;};function add(q, value) {if (length > options.cacheLength){flush();}if (!data[q]){length++;}data[q] = value;}function populate(){if( !options.data ) return false;// track the matchesvar stMatchSets = {},nullData = 0;// no url was specified, we need to adjust the cache length to make sure it fits the local data storeif( !options.url ) options.cacheLength = 1;// track all options for minChars = 0stMatchSets[""] = [];// loop through the array and create a lookup structurefor ( var i = 0, ol = options.data.length; i < ol; i++ ) {var rawValue = options.data[i];// if rawValue is a string, make an array otherwise just reference the arrayrawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;var value = options.formatMatch(rawValue, i+1, options.data.length);if ( value === false )continue;var firstChar = value.charAt(0).toLowerCase();// if no lookup array for this character exists, look it up nowif( !stMatchSets[firstChar] )stMatchSets[firstChar] = [];// if the match is a stringvar row = {value: value,data: rawValue,result: options.formatResult && options.formatResult(rawValue) || value};// push the current match into the set liststMatchSets[firstChar].push(row);// keep track of minChars zero itemsif ( nullData++ < options.max ) {stMatchSets[""].push(row);}};// add the data items to the cache$.each(stMatchSets, function(i, value) {// increase the cache sizeoptions.cacheLength++;// add to the cacheadd(i, value);});}// populate any existing datasetTimeout(populate, 25);function flush(){data = {};length = 0;}return {flush: flush,add: add,populate: populate,load: function(q) {if (!options.cacheLength || !length)return null;/** if dealing w/local data and matchContains than we must make sure * to loop through all the data collections looking for matches*/if( !options.url && options.matchContains ){// track all matchesvar csub = [];// loop through all the data grids for matchesfor( var k in data ){// don't search through the stMatchSets[""] (minChars: 0) cache// this prevents duplicatesif( k.length > 0 ){var c = data[k];$.each(c, function(i, x) {// if we've got a match, add it to the arrayif (matchSubset(x.value, q)) {csub.push(x);}});}}return csub;} else// if the exact item exists, use itif (data[q]){return data[q];} elseif (options.matchSubset) {for (var i = q.length - 1; i >= options.minChars; i--) {var c = data[q.substr(0, i)];if (c) {var csub = [];$.each(c, function(i, x) {if (matchSubset(x.value, q)) {csub[csub.length] = x;}});return csub;}}}return null;}};};$.Autocompleter.Select = function (options, input, select, config) {var CLASSES = {ACTIVE: "ac_over"};var listItems,active = -1,data,term = "",needsInit = true,element,list;// Create resultsfunction init() {if (!needsInit)return;element = $("<div/>").hide().addClass(options.resultsClass).css("position", "absolute").appendTo(document.body);list = $("<ul/>").appendTo(element).mouseover( function(event) {if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));$(target(event)).addClass(CLASSES.ACTIVE);}}).click(function(event) {$(target(event)).addClass(CLASSES.ACTIVE);select();// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focusinput.focus();return false;}).mouseout(function() {$("li").removeClass(CLASSES.ACTIVE);active =-1;}).mousedown(function() {config.mouseDownOnSelect = true;}).mouseup(function() {config.mouseDownOnSelect = false;});if( options.width > 0 )element.css("width", options.width);needsInit = false;}function target(event) {var element = event.target;while(element && element.tagName != "LI")element = element.parentNode;// more fun with IE, sometimes event.target is empty, just ignore it thenif(!element)return [];return element;}function moveSelect(step) {listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);movePosition(step);var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);if(options.scroll) {var offset = 0;listItems.slice(0, active).each(function() {offset += this.offsetHeight;});if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) { list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());} else if(offset < list.scrollTop()) {list.scrollTop(offset);}}};function movePosition(step) {active += step;if (active < 0) {active = listItems.size() - 1;} else if (active >= listItems.size()) {active = 0;}}function limitNumberOfItems(available) {return options.max && options.max < available? options.max: available;}function fillList() {list.empty();var max = limitNumberOfItems(data.length);for (var i=0; i < max; i++) {if (!data[i])continue;var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);if ( formatted === false )continue;var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];$.data(li, "ac_data", data[i]);}listItems = list.find("li");if ( options.selectFirst ) {listItems.slice(0, 1).addClass(CLASSES.ACTIVE);active = 0;}// apply bgiframe if availableif ( $.fn.bgiframe )list.bgiframe();}return {display: function(d, q) {init();data = d;term = q;fillList();},next: function() {if(active+1==data.length){$(input).val(term);$("li").removeClass(CLASSES.ACTIVE);active=-1;}else{moveSelect(1);$(input).val($(data[active]).val());}},prev: function() {if(active-1==-1){$(input).val(term);$("li").removeClass(CLASSES.ACTIVE);active=data.length;}else{moveSelect(-1);$(input).val($(data[active]).val());}},pageUp: function() {if (active != 0 && active - 8 < 0) {moveSelect( -active );} else {moveSelect(-8);}},pageDown: function() {if (active != listItems.size() - 1 && active + 8 > listItems.size()) {moveSelect( listItems.size() - 1 - active );} else {moveSelect(8);}},hide: function() {element && element.hide();listItems && listItems.removeClass(CLASSES.ACTIVE);active = -1;},visible : function() {return element && element.is(":visible");},current: function() {return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);},show: function() {var offset = $(input).offset();element.css({width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),top: offset.top + input.offsetHeight,left: offset.left}).show();if(options.scroll) {list.scrollTop(0);list.css({maxHeight: options.scrollHeight,overflow: 'auto'});if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {var listHeight = 0;listItems.each(function() {listHeight += this.offsetHeight;});var scrollbarsVisible = listHeight > options.scrollHeight;list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );if (!scrollbarsVisible) {// IE doesn't recalculate width when scrollbar disappearslistItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );}}}},selected: function() {var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);return selected && selected.length && $.data(selected[0], "ac_data");},emptyList: function (){list && list.empty();},unbind: function() {element && element.remove();}};};$.Autocompleter.Selection = function(field, start, end) {if( field.createT extRange ){var selRange = field.createTextRange();selRange.collapse(true);selRange.moveStart("character", start);selRange.moveEnd("character", end);selRange.select();} else if( field.setSelectionRange ){field.setSelectionRange(start, end);} else {if( field.selectionStart ){field.selectionStart = start;field.selectionEnd = end;}}field.focus();};})(jQuery);另外附一个样式文件,jquery.autocomplete.css:* {margin: 0px; }/***提示层的样式,除颜色及字体、边框等,其他样式请勿随意更改**/.ac_results {padding: 0px;border: 1px solid #CCCCCC;background-color: white;overflow: hidden;z-index: 99999;}.ac_results ul {width: 100%;list-style-position: outside;list-style: none;padding: 0;margin: 0;}/*提示内容的样式*/.ac_results li {margin: 0px;padding: 2px 5px;cursor: default;display: block;font-size:17px;color:#333333;line-height: 19px;font-weight:Bold;overflow: hidden;}/*加载时的样式,一个小loading图片,大家可以随便改*/.ac_loading {background: white url('images/loading.gif') right center no-repeat; }/*提示层内奇数行的样式,比如隔一行显示的背景色不同等*/.ac_odd {background-color: #FFFFFF;}/*鼠标放上去时候的样式,此处仅仅改背景色*/.ac_over {background-color: #DEE4E4;}。