Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2397485
  • 博文数量: 328
  • 博客积分: 4302
  • 博客等级: 上校
  • 技术积分: 5486
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-01 11:14
个人简介

悲剧,绝对的悲剧,悲剧中的悲剧。

文章分类

全部博文(328)

文章存档

2017年(6)

2016年(18)

2015年(28)

2014年(73)

2013年(62)

2012年(58)

2011年(55)

2010年(28)

分类: jQuery

2015-03-29 11:49:31

jQuery.Autocomplete 是jquery的流行插件,能够很好的实现输入框的自动完成(autocomplete)、建议提示(input suggest)功能,支持ajax数据加载。
官方网站:

官网上的一个完整的简单例子:
  1. <!doctype html>
  2. <html lang="en">
  3. <head>
  4.   <meta charset="utf-8">
  5.   <title>jQuery UI Autocomplete - Default functionality</title>
  6.   <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  7.   <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  8.   <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  9.   <link rel="stylesheet" href="/resources/demos/style.css">
  10.   <script>
  11.   $(function() {
  12.     var availableTags = [
  13.       "ActionScript",
  14.       "AppleScript",
  15.       "Asp",
  16.       "BASIC",
  17.       "C",
  18.       "C++",
  19.       "Clojure",
  20.       "COBOL",
  21.       "ColdFusion",
  22.       "Erlang",
  23.       "Fortran",
  24.       "Groovy",
  25.       "Haskell",
  26.       "Java",
  27.       "JavaScript",
  28.       "Lisp",
  29.       "Perl",
  30.       "PHP",
  31.       "Python",
  32.       "Ruby",
  33.       "Scala",
  34.       "Scheme"
  35.     ];
  36.     $( "#tags" ).autocomplete({
  37.       source: availableTags
  38.     });
  39.   });
  40.   </script>
  41. </head>
  42. <body>
  43.  
  44. <div class="ui-widget">
  45.   <label for="tags">Tags: </label>
  46.   <input id="tags">
  47. </div>
  48.  
  49.  
  50. </body>
  51. </html>


一 数据源的指定


此功能最主要的参数是source,设置匹配菜单中的数据项,设置方式:

1、string数组参数,格式:[ "Choice1", "Choice2" ]

  1. 初始化时:
  2. $( ".selector" ).autocomplete({ source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] });


  3. 初始化后
  4. // getter
  5. var source = $( ".selector" ).autocomplete( "option", "source" );
  6.    
  7.    
  8. // setter
  9. $( ".selector" ).autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] );

2、object数组参数,格式[ { label: "Choice1", value: "value1" }, ... ]

其中label是在匹配菜单中显示项的值,而value,是选中此匹配项后,append到中的真实值

3、string参数

如果是string参数,则是指定一个远程的数据源,然后当中有输入变化,即change事件后,会自动将输入的内容,以GET方式发送到远程数据源,其中输入内容以term参数保存;
例如,参数为,那么在用户输入abc后,将会发送一个GET请求如?term=abc
返回的结果必须以json格式,数据格式如上面1、2描述
然后在服务器端接收,并输出相应结果,注意默认传递的参数名称为term:
  1. public void ProcessRequest(HttpContext context)
  2. {
  3.     // 查询的参数名称默认为term
  4.     string query = context.Request.QueryString["term"];
  5.     context.Response.ContentType = "text/javascript";
  6.     //输出字符串数组 或者 JSON 数组
  7.     context.Response.Write("[{\"label\":\"博客园\",\"value\":\"cnblogs\"},{\"label\":\"囧月\",\"value\":\"囧月\"}]");
  8. }


4、function参数,格式 Function( Object request, Function response( Object data ) )

这种参数最灵活,可以让你以自己的方式向服务器发出查询,并自己解析数据,最后将数据回写到response即可
  1. $ ( ".selector" ). autocomplete ({
  2.   source: function(request,response){
  3.     //获取用户输入
  4.     var term = request.term;
  5.     //根据自定义方式从服务器获取数据
  6.     ...
  7.     //还可以自己解析数据
  8.     ..
  9.     //最后把数据按照前面1、2描述的格式,放到response中
  10.     response(data);
  11.   }
  12. });
一个例子:
  1. var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "火星.com", "囧月.com"];
  2. $("#email1").autocomplete({
  3.     autoFocus: true,
  4.     source: function(request, response) {
  5.         var term = request.term, //request.term为输入的字符串
  6.             ix = term.indexOf("@"),
  7.             name = term, // 用户名
  8.             host = "", // 域名
  9.             result = []; // 结果
  10.  
  11.         result.push(term);
  12.         // result.push({ label: term, value: term }); // json格式
  13.         if (ix > -1) {
  14.             name = term.slice(0, ix);
  15.             host = term.slice(ix + 1);
  16.         }
  17.         if (name) {
  18.             var findedHosts = (host ? $.grep(hosts, function(value) {
  19.                 return value.indexOf(host) > -1;
  20.             }) : hosts),
  21.             findedResults = $.map(findedHosts, function(value) {
  22.                 return name + "@" + value; //返回字符串格式
  23.                 // return { label: name + " @ " + value, value: name + "@" + value }; // json格式
  24.             });
  25.             result = result.concat($.makeArray(findedResults));
  26.         }
  27.         response(result);//呈现结果
  28.     }
  29. });


二 功能支持:


此自动补全功能,支持'; tpl += '
'; tpl += '
'; tpl += '
'; tpl += ''; tpl += '
'; tpl += '
'; tpl += '
'; $('.z_move_comment').html(''); $(this).parents('.Blog_right1_8').find('.z_move_comment').html(tpl).show(); }); //引用的评论提交 $('#quota_sbumit').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var bid = $(this).attr('bid'); var tid = $(this).attr('tid');//被引用人的id var qid = $(this).attr('cid');//引用的id var url = $(this).attr('url'); var text = $('#rmsg').val(); var tname = $(this).attr('tname'); if(text == '' || text=='文明上网,理性发言...') { showErrorMsg('评论内容不能为空!' , '消息提示'); return false; } else { if(mb_strlen(text) > 1000){ showErrorMsg('评论内容不能超过500个汉字' , '消息提示'); return false; } } $.ajax({ type: "post", url: url , data: {'bid': bid , 'to' : tid , 'qid' : qid , 'text': text , 'tname' : tname }, dataType: 'json', success: function(data){ if(data.code == 1){ var tpl = '
'; tpl+= ''; tpl+= '
'; tpl+= '

' + data.info.username + '' + data.info.dateline + '

'; tpl+= '

' + data.info.quota.username + ':'+ data.info.quota.content + '

'; tpl+= '

' + data.info.content + '

回复 |  删除 |  举报
'; tpl+= ''; tpl+= '
'; $('#replyList .Blog_right1_8:first').before(tpl); $('.z_move_comment').html('').hide(); } else if(data.code == -1){ //showErrorMsg(data.info , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); } }, error: function(){//请求出错处理 } }); }); //底部发表评论 $('#submitmsg').click(function(){ if(allowComment == 1) { showErrorMsg('该博文不允许评论' , '消息提示'); return false; } var bid = $(this).attr('bid'); var toid = $(this).attr('toid'); var text = $('#reply').val(); var url = $(this).attr('url'); if(text == '' || text=='文明上网,理性发言...') { showErrorMsg('评论内容不能为空!' , '消息提示'); return false; } else { if(mb_strlen(text) > 1000){ showErrorMsg('评论内容不能超过500个汉字' , '消息提示'); return false; } } $.ajax({ type: "post", url: url , data: {'bid': bid , 'to' : toid ,'text': text}, dataType: 'json', success: function(data){ if(data.code == 1) { var tpl = '
'; tpl += ''; tpl += '
'; tpl += '

' + data.info.username + '' + data.info.dateline + '

'; tpl += '

' + data.info.content + '

'; tpl += '
回复 |  删除 |  举报
'; tpl += ''; tpl += '
'; $('.Blog_tit3:first').after(tpl); $('#reply').val('文明上网,理性发言...'); } else if(data.code == -1) { showErrorMsg(data.info , '消息提示'); } }, error: function(){//请求出错处理 } }); }); //底部评论重置 $('#reset_comment').click(function(){ $('#reply').val('文明上网,理性发言...'); }); //取消回复 $('#qx_comment').live('click' , function(){ $('.z_move_comment').html('').hide(); }); $('#rmsg, #reply').live({ focus:function(){ if($(this).val() == '文明上网,理性发言...'){ $(this).val(''); } }, blur:function(){ if($(this).val() == ''){ $(this).val('文明上网,理性发言...'); } } }); //删除留言确认 $('.comment_del_mark').live('click' , function(){ var url = $(this).attr('url'); asyncbox.confirm('删除留言','确认', function(action){ if(action == 'ok') { location.href = url; } }); }); //删除时间确认 $('.del_article_id').click(function(){ var delurl = $(this).attr('delurl'); asyncbox.confirm('删除文章','确认', function(action){ if(action == 'ok') { location.href = delurl; } }); }); /* //字数限制 $('#rmsg, #reply').live('keyup', function(){ var id = $(this).attr('id'); var left = Util.calWbText($(this).val(), 500); var eid = '#errmsg'; if(id == 'reply') eid = '#rerrmsg'; if (left >= 0) $(eid).html('您还可以输入' + left + '字'); else $(eid).html('您已超出' + Math.abs(left) + ''); }); */ //加载表情 $('#face').qqFace({id : 'facebox1', assign : 'reply', path : '/image/qqface/'}); $('#mface').qqFace({id : 'facebox', assign : 'rmsg', path:'/image/qqface/'}); /* $('#class_one_id').change(function(){ alert(123213); var id = parseInt($(this).val() , 10); if(id == 0) return false; $('.hidden_son_class span').each(function( index , dom ){ if( dom.attr('cid') == id ) { } }); }); */ //转载文章 var turn_url = "/blog/viewClassPart.html"; $('#repost_bar').click(function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var id = $(this).attr('bid'); asyncbox.open({ id : 'turn_class_thickbox', url : turn_url, title : '转载文章', width : 330, height : 131, scroll : 'no', data : { 'id' : id }, callback : function(action){ if(action == 'close'){ $.cover(false); } } }); }); /* //转发文章 $('#repost_bar').live('click' , function(){ if(isOnLine == '' ) { //showErrorMsg('登录之后才能进行此操作' , '消息提示'); showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); return false; } var bid = $(this).attr('bid'); var url = $(this).attr('url'); asyncbox.confirm('转载文章','确认', function(action){ if(action == 'ok'){ $.ajax({ type:"POST", url:url, data: { 'bid' : bid }, dataType: 'json', success:function(msg){ if(msg.error == 0){ showSucceedMsg('转发成功!', '消息提示'); }else if(msg.error == 1){ //location.href = '/index.php?r=site/login'; showErrorMsg('操作失败,您需要先登录!', '消息提示', 'http://account.chinaunix.net/login'); }else{ showErrorMsg(msg.error_content, '消息提示'); } } }); } }); }); */ });