標籤:
使用typeahead.js可以實現預先輸入,即智能提示,本篇在ASP.NET MVC下實現。實現效果如下:
首先是有關城市的模型。
public class City
{ public int Id { get; set; } public string Name { get; set; } public string PinYin { get; set; } }
在HomeController中響應前端請求返回有關City的json資料。
public ActionResult GetCitiesJson()
{ var result = new List<City>()
{ new City(){Id = 1, Name = "青島",PinYin = "qingdao"}, new City(){Id = 10, Name = "青山",PinYin = "qingshan"}, new City(){Id = 11, Name = "青峰",PinYin = "qingfeng"}, new City(){Id = 2, Name = "武漢",PinYin = "wuhan"}, new City(){Id = 3, Name = "煙台",PinYin = "yantai"}, new City(){Id = 4, Name = "哈爾濱",PinYin = "haerbing"}, new City(){Id = 5, Name = "北京",PinYin = "beijing"}, new City(){Id = 6, Name = "安陽",PinYin = "angyang"}, new City(){Id = 7, Name = "長春",PinYin = "changchun"}, new City(){Id = 8, Name = "東陽",PinYin = "dongyang"}, new City(){Id = 9, Name = "葛洲壩",PinYin = "gezhoubei"} };
return Json(result,JsonRequestBehavior.AllowGet);
}
在視圖中先載入City集合,再使用預先輸入功能。
@section styles
{ <link href="~/Content/TypeHead.css" rel="stylesheet" />
}
<div style="margin: 50px;">
<input class="typeahead" type="text" placeholder="輸入城市名稱">
</div>
@section scripts
{ <script src="~/Scripts/typeahead.bundle.js"></script>
<script type="text/javascript">
$(function () { $.getJSON(‘@Url.Action("GetCitiesJson","Home")‘, function(data) { if (data) { $.each(data, function(index, city) { cities.push(city.Name);
});
}
});
//預先輸入功能
$(‘.typeahead‘).typeahead({ hint: true,
highlight: true,
minLength: 1
},
{ name: ‘city‘,
displayKey: ‘value‘,
source: substringMatcher(cities)
});
});
var cities = [];
//參數arr表示資料來源 數組
var substringMatcher = function (arr) { return function findMatches(q, cb) { var substrRegex;
var matches = [];
substrRegex = new RegExp(q, ‘i‘);
$.each(arr, function (i, ele) { if (substrRegex.test(ele)) { matches.push({ value: ele }); }
});
cb(matches);
};
};
</script>
}
如何同時支援拼音和漢字的預先輸入、智能提示呢?My dear friends, Any idea?
在ASP.NET MVC中使用typeahead.js支援預先輸入,即智能提示