最近研究了一下自动补全插件,由于所用框架为bootstrap
找的都是往这边靠的,查了一下资料,在bootstrap 2.x时,其自带了补全控件typeahead。
后面升到bootstrap 3.x时,舍弃了这个插件,这是出现了单独插件,名叫bootstrap-3-typeahead。
再后面bootstrap-3-typeahead 改名 typeahead.js。
说一下演变过程,大家看的时候别弄错了。这篇文章为适配bootstrap 3.x的typeahead.js插件。
来自twitter的自动补全插件。
官方地址:http://twitter.github.io/typeahead.js/
github:https://github.com/twitter/typeahead.js/
推荐自己照着学的博文:http://ju.outofmemory.cn/entry/155452
很全,尼玛坑爹的百度都没搜到,还是bing搜到的,再次推荐大家远离百度,珍惜时间
下面上自己亲测可用的代码:
HTML:
<div class="row">
<label for="txbTitle" class="control-label col-sm-2">收文者:</label>
<div class="col-sm-10" id="Recipient" >
<asp:TextBox runat="server" id="txbRecipient" CssClass="typeahead form-control"
placeholder="收文者" />
<div id="selectedItems" ></div>
</div>
<input id="selectedRecipients" type="hidden"/>
</div>
JS:
$(function () {
/*** 1.远程数据示例 ***/
var engine_user = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
// 在文本框输入字符时才发起请求
remote: {
url: 'TradHandler.ashx?q=%QUERY&request=typeaheadData',
wildcard: '%QUERY'
}
});
engine_user.initialize();
$('#Recipient .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'provinces',
displayKey: 'name',
source: engine_user
}).on('typeahead:selected', function (e, datum) {
var selectItemVal = $("#selectedRecipients").val().substr(0, $("#selectedRecipients").val().length - 2);
var arr = selectItemVal.split("@@");
if ($.inArray(datum["rkey"]+"",arr)>=0)
{ } else {
$("#selectedItems").append("<span class='label label-primary' style='cursor:pointer' οnclick='removeSelected(this," + datum["rkey"] + ")'><span class='glyphicon glyphicon-minus' aria-hidden='true'></span> " + datum["name"] + "</span> ");
$("#selectedRecipients").val($("#selectedRecipients").val() + datum["rkey"] + "@@");
$('#Recipient .typeahead').blur();
}
});
});
//移除已选择项
function removeSelected(opt,removeId)
{
$(opt).remove();
var selectRkey = $("#selectedRecipients").val();
var arr = selectRkey.split("@@");
var arr2 = $(arr).map(function (ind,val) {
if (parseInt(val) == parseInt(removeId)) {
//arr.remove
} else {
return val;
}
}).get().join("@@");
$("#selectedRecipients").val(arr2);
}
提供数据的Handler:
/// <summary>
/// 自动补全
/// </summary>
private void typeaheadData(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
List<SimpleModel> list = new List<SimpleModel>();
for (int i = 0; i < 1000; i++)
{
list.Add(new SimpleModel() { age = 18, name = "小李" + i, rkey = i + 1, sex = "男" });
}
List<SimpleModel> getList;
string searchKey = context.Request.Params["q"];
if (!string.IsNullOrEmpty(searchKey))
{
getList = list.Where(t => t.name.Contains(searchKey)).ToList();
}
else
{
getList = list;
}
context.Response.Write(jss.Serialize(getList));
}
效果如下:(我这里是可多选,点击标签移除,大家对号入座)
先到这。有问题留言