jquery+ajax 类百度输入框
这篇文章,一拖再拖,明日何其多,正好今天元气满满,就简单写完
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery 自动完成(Autocomplete) - 分类</title> <link rel="stylesheet" href="css/jquery-ui.min.css"> <script src="js/jquery.min.js"></script> <script src="js/jquery-ui.min.js"></script> <style> .ui-autocomplete-category { font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; } </style> <script> $(function() { $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var that = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" ); currentCategory = item.category; } that._renderItemData( ul, item ); }); } }); var d1 = "anders"; var d2 = "Products"; var data = [ { label: d1, category: "" }, { label: d1, category: "" }, { label: d1, category: "" }, { label: d1, category: "Products" }, { label: "annk K12", category: "Products" }, { label: "annttop C13", category: "Products" }, { label: "anders andersson", category: "People" }, { label: "andreas andersson", category: "People" }, { label: "andreas johnson", category: "People" } ]; $( "#search" ).catcomplete({ delay: 0, source: data }); }); </script> </head> <body> <input id="search"> </body> </html>
效果查看:
有人就想,我要ajax请求后台,动态获取怎么写?
以下是关键代码
$(function() { $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var that = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" ); currentCategory = item.category; } that._renderItemData( ul, item ); }); } }); var option = { max: 12, //列表里的条目数 minChars: 0, //自动完成激活之前填入的最小字符 width: 400, //提示的宽度,溢出隐藏 scrollHeight: 300, //提示的高度,溢出显示滚动条 matchContains: false, //包含匹配,就是data参数里的数据,是否只要包含文本框里的数据就显示 autoFill: true, //自动填充 minLength: 0, select: function (event, ui) { selectEnterprise(ui.item.id);//根据选择获取选中id } }; var dataArray=[]; $.ajax({ url: '${ctx}/enterprise/enterprise/autocomplete', type: 'post', dataType: 'json', success: function(data){ for(var i=0; i<data.length; i++){ var vo = data[i]; dataArray.push({label: vo.label,category: vo.category,id : vo.id}); } } }) $( "#tempName" ).catcomplete({source: dataArray},option).on('focus', function(){$(this).keydown();}); });
代码下载:https://github.com/FlyWithFish/project