写一个WebService方法GetAuto
[WebMethod]
public List<CityInfo> GetCityLike(string prefix)
{
List<CityInfo> m = new List<CityInfo>();
CityInfo a = new CityInfo();
a.CityCode = prefix.ToUpper();
foreach (CityInfo g in City.GetCityByLike(a))
{
m.Add(g);
}
return m;
}
在前台aspx页面写jq方法(引用jq库)
<script src="../JQuery/jquery-1.10.2.js" type="text/javascript"></script>
添加2个标签一个用于搜索框一个用于填充数据
<div style="position:relative;float:left;width: 140px;">
<asp:TextBox runat="server" ID="txtType" Text="" class="Text_float" οnkeyup="autoType()"/>
<ul id="ulType" style="margin:0;padding:0; position:absolute;max-height:200px;height:auto;overflow-y:scroll; background:#fff;border:1px solid #898184;display:none; color:#8C4510;" ></ul>
</div>
jq方法
<script type="text/javascript">
function autoType() { //1
var Service = '<%=ResolveUrl("../WebService/GetAuto.asmx/GetCityLike") %>';
var key = $("#txtType").val();
var tipHtml = ""; //拼接HTML标签
$.ajax({
url: Service,
data: "{'prefix': '" + key + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length <= 0) { $("#ulType").html("<li>没有找到数据!</li>"); return; } else $("#ulType").show();
$.each(data.d, function () {
tipHtml += "<li>" + this.type + "</li>";
})
var wid = parseInt($("#txtType").width());
var left = parseInt($("#txtType").offset().left);
var top = parseInt($("#txtType").offset().top);
var height = parseInt($("#txtType").height());
//将拼接好的html代码显示并设置ul的宽度始终与文本框一样
$("#ulType").html(tipHtml).width(wid);
//设置ul显示位置始终处于文本框之下。
$("#ulType").css("position", "absolute").css("left", 0).css("top", height + 5);
$(function () { //5
$("#ulType li").mouseover(function () {
$(this).css("background", "#00ffee").siblings("li").css("background", "#fff");
});
$("#ulType li").click(function () {
$("#ulType").hide();
$("#txtType").val($(this).text());
});
})//5
}
});
} //1
$(document).click(function (e) {//点击除了搜索框外其他位置隐藏清空填充数据标签内容
var isTarget = $(e.target).closest("#txtType").length;
if (isTarget) {
} else {
$("#ulType").hide();
$("#ulType").empty();
}
});
</script>