============================================================================
原创作品,允许转载。转载时请务必以超链接形式标明原始出处、以及本声明。
请注明转自:http://yunjianfei.iteye.com/blog/
============================================================================
在制作HTML页面的时候,难免会遇到级联下拉列表的显示。比如最常见的 “省---市” 级联下拉列表。
下面贴出来我的实现方式,供大家参考一下(用的是jquery)。
首先是运行结果:
下面是代码,可以详细看看。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="./jquery-2.1.0.min.js"></script>
<script>
$.fn.extend({
parent_select_change: function(province) {
$("#child_select").empty();
var parent = $("#parent_select").val();
if (parent == ''){
return false;
}
var cities = null;
for(var i=0; i < province.length; i++) {
var p = province[i];
if(p.id == parent){
cities = p.city;
break;
}
}
for(var i=0; i < cities.length; i++) {
city = cities[i];
var o = new Option(city.name,city.cid);
$("#child_select").append(o);
}
},
show_province_items: function() {
var resp = [
{
"id" : 1,
"name" : "山西",
"city" : [{
"cid" : 1,
"name" : "太原",
}, {
"cid" : 2,
"name" : "临汾",
}
],
},
{
"id" : 2,
"name" : "陕西",
"city" : [{
"cid" : 3,
"name" : "榆林",
}, {
"cid" : 4,
"name" : "西安",
}
],
},
];
//以上为模拟数据,可以用getJSON的方式,从服务器端取回来数据
//$.getJSON("/province", function(resp){
var html = ""
var pro = resp
html += "<option value=''> --请选择-- </option>"
if(pro){
for(var i=0; i < pro.length; i++) {
var p = pro[i];
html += "<option value='" + p.id + "'>" + p.name + "</option>"
}
}
$("#parent_select").empty();
$("#parent_select").html(function(i,origText){
return html;
});
$("#parent_select").change(function(){
$(this).parent_select_change(pro);
});
//});
}
});
$(document).ready(function(){
$(this).show_province_items();
});
</script>
</head>
<body>
<center>
<h1>级联列表</h1>
省:<select id='parent_select' name='province'></select> 市:<select id='child_select' name='city'></select>
<br>
</center>
</body>
</html>