jQuery实现下拉搜索框

要做一个全国省份的选择框,由于选项太多,不适合用<select>标签

因此选择用jQuery来写,用一个<ul>来显示提示的内容,使用方向箭头来移动,Enter键来确定

html代码如下:

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <title>省份自动补全</title>
 5     <script src="js/jquery-2.1.0.min.js" type="text/javascript"></script>
 6     <script src="js/provinces.js" type="text/javascript"></script>
 7     <style type="text/css">
 8         ul, li{list-style-type: none;}
 9     </style>
10 </head>
11 
12 <body>
13     <input id="province" type="text" onkeyup="selectItem(this.value, event)" />    
14     <ul id="ulItems" style="display:none; border:1px solid #cecece; border-top: none;" >
15     </ul>
16 </body>

 

js代码如下:

var currentIndex = -1;
var oldIndex = -1;
function selectItem(keyword, event) {
	if ("" == keyword.tr) {
		$("#ulItems").hide();
		return;
	} else {
		// 根据关键词产生列表
		$("#ulItems li").remove();
		autoComplete(keyword);
		var liLength = $("#ulItems li").length;
		if (liLength > 0) {
			oldIndex = currentIndex;
			// 上移
			if (38 == event.keyCode) {
				if (0 == currentIndex) {
					currentIndex = liLength - 1;
				} else {
					currentIndex--;
					if (currentIndex < 0) {
						currentIndex = liLength - 1;
					}
				}
				if (currentIndex != -1) {
					var li_item = $("#ulItems li").eq(currentIndex);
					$(li_item).css({
						'backgroundColor': '#3366CC'
					});
				}
				if (oldIndex != -1) {
					var li_item = $("#ulItems li").eq(oldIndex);
					$(li_item).css({
						'backgroundColor': '#fff'
					});
				}
			}
			// 下移
			if (40 == event.keyCode) {
				if (liLength -1 == currentIndex) {
					currentIndex = 0;
				} else {
					currentIndex++;
					if (currentIndex > liLength - 1) {
						currentIndex = 0;
					}
				}
				if (currentIndex != -1) {
					var li_item = $("#ulItems li").eq(currentIndex);
					$(li_item).css({
						'backgroundColor': '#3366CC'
					});
				}
				if (oldIndex != -1) {
					var li_item = $("#ulItems li").eq(oldIndex);
					$(li_item).css({
						'backgroundColor': '#fff'
					});
				}
			}
			// Enter确定选择
			if (13 == event.keyCode) {
				var li_value = $("#ulItems li").eq(currentIndex).text();
				$("#province").val(li_value);
				$("#ulItems").hide();
			}
		}
	}	
}

function autoComplete(keyword) {
	var province = [ "北京", "天津", "上海", "重庆",
		"河北", "河南", "云南", "辽宁", "黑龙江", "湖南",
		"安徽", "山东", "新疆", "江苏", "浙江", "江西",
		"湖北", "广西", "甘肃", "山西", "内蒙古", "陕西",
		"吉林", "福建", "贵州", "广东", "青海", "西藏",
		"四川", "宁夏", "海南", "台湾", "香港", "澳门"];
	for (var item in province) {
		if (province[item].indexOf(keyword) >= 0) {
			var liItem = "<li>" + province[item] + "</li>";
			$("#ulItems").append(liItem);
		}
	}
	$("#ulItems").show();
}

  

posted @ 2014-04-17 13:03  kotomifi  阅读(332)  评论(0)    收藏  举报

@盛夏