前端联想下拉框的实现

来源:互联网 发布:linux发送邮件超时 编辑:程序博客网 时间:2024/05/16 00:45

当用户输入字符时,前端可自动联想出用户输入的字符,下拉框可以增加界面的友好性,这种提示功能可通过开源框架typeahead来实现。

首先该功能需要包含以下JS文件:

<script src="../../Scripts/jquery.min.js" type="text/javascript"></script><script src="../../Scripts/bloodhound.js" type="text/javascript"></script><script src="../../Scripts/typeahead.bundle.js" type="text/javascript"></script><script src="../../Scripts/typeahead.jquery.js" type="text/javascript"></script>
假设前端的下拉框html代码如下:

<h2>Suggestion</h2> <div id="container"><input class="typeahead" type="text" size="400" placeholder="suggestion"></div>
JS初始化代码如下:

<script>var bestPictures = new Bloodhound({  datumTokenizer: Bloodhound.tokenizers.obj.nonword('value'),  queryTokenizer: Bloodhound.tokenizers.nonword,  limit: 10,//最多显示10条数据  remote: {    url:'/home/suggest?keyword=%QUERY',//查询的URL,%QUERY为通用符,用于提交后台参数,当需要增加新的参数时就需要修改这里    wildcard:'%QUERY'  }});bestPictures.initialize();$('#container .typeahead').typeahead( {  hint: true,  highlight: true,  minLength: 1}, {  name: 'best-pictures',  displayKey: function(item) {    return item;//返回JSON数组中的每个元素用于显示  },  limit:10,  source: bestPictures.ttAdapter(),});</script>
如需增加新的参数可修改remote配置,如:

remote: {                                    url:'/home/json/suggestion?key=%QUERY&team=%TEAM',replace:function(url,query) {       var team = $("# team").val();      return url.replace("%QUERY",query).replace('%TEAM',team);}
后端/home/suggestion对应的Action如下:

public ActionResult Suggest(){     string query = this.Request.QueryString["keyword"];       string[] s = { "hello","test"};       return Json(s, JsonRequestBehavior.AllowGet);}





0 0
原创粉丝点击