jquery 搜索自动提示(autocomplete插件用法)
1.用autocomplete插件前要加载,(js文件和css样式文件)两个文件
<script src="/javascripts/jquery-ui-1.8.14.custom.min.js" language="javascript"></script>
<link href="/stylesheets/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css"/>
?
?
2.如果不用与数据库链接,则直接写如下代码:
?
$(document).ready(function(){ var array_tags=['iphone','ipad','nok','moto']; $("#tj_tags").autocomplete({ source: array_tags //source中添加的是一组数组 });});?
?
?
3.如果要从数据库中取数据,则就要添加ajax请求,代码如下:
//这段代码,在下拉框中实现你想要出现的效果//item:表示每一行的一个值//ul:不用管它直接写上就可以了(它代表你每一行要添加到哪里的div或其它)$(document).ready(function(){$.ui.autocomplete.prototype._renderItem = function (ul, item) { return $("<li></li>") .data("item.autocomplete", item) .append("<a>" + item.label + "<span style='float:right;'>约<font style='color:#f50;'>"+item.amount+"</font>件产品</span></a>") .appendTo(ul); }; //这里的ajax返回类型可以随自己定义,本代码后台把字符串传给前台,$("#tj_tags").autocomplete({ source: function(request, response){$.ajax({url: "/w/find_related_records",type: "GET",data: { keyword : $('#tj_tags').val() },success:function(xml_data){var tj_array=xml_data.split("_"); //代码是通过"_"分割response($.map(tj_array,function(item){return {label:item.split("***")[0], //这里的label与amount与上面代码中用到的密切相关amount:item.split("***")[1]}}));}});},minLength: 1 //搜索时,最少1个字符时出结果});});?
?
3.界面中的代码
<input id="tj_tags" name="q" type="text" autocomplete="off" value="ip" />
?
?
4.效果图
?
?