以前都是用的服务器端的控件,绑定数据很随意,级联也很随意,现在要考虑用客户端控件,突然有点蛋疼,以前没怎么写过,今天认真写一个
在网上找得例子,再完善一下:嘻嘻
<script type="text/javascript">
var cityArr=[];
cityArr['Shanghai']=[
{txt:'zhabei',val:'zhabei'},
{txt:'huangpu',val:'huangpu'},
{txt:'baoshan',val:'baoshan'},
{txt:'xuhui',val:'xuhui'},
{txt:'yangpu',val:'yangpu'},
{txt:'hongkou',val:'hongkou'}
];
cityArr['Jiangsu'] = [
{txt:'nanjing', val:'nanjing'},
{txt:'wuxi', val:'wuxi'},
{txt:'xuzhou', val:'xuzhou'},
{txt:'suzhou', val:'suzhou'},
{txt:'nantong', val:'nantong'},
{txt:'huaiyin', val:'huaiyin'},
{txt:'yangzhou', val:'yangzhou'},
{txt:'zhenjiang', val:'zhenjiang'},
{txt:'changzhou', val:'changzhou'}
];
function setCity(province)
{
setSelectOption('city',cityArr[province],'-please select-');
}
function noneSelected(province)
{
removeOptionsExcept('city');
}
</script>
<script type="text/javascript">
function setSelectOption(selectObj,optionList,firstOption,selected)
{
if(typeof selectObj!='object')
{ selectObj=document.getElementById(selectObj) };
//Empty the select
removeOptions(selectObj);
var start=0;
if(firstOption)
{
selectObj.options[0]=new Option(firstOption,'');
start ++;
}
var len=optionList.length;
for(var i=0;i<len;i++)
{
selectObj.options[start]=new Option(optionList[i].txt,optionList[i].val);
if(selected==optionList[i].val)
{
selectObj.options[start].selected=true;
}
start ++;
}
}
function removeOptions(selectObj)
{
if (typeof selectObj != 'object')
{ selectObj = document.getElementById(selectObj); }
// 原有选项计数
var len = selectObj.options.length;
for (var i=0; i < len; i++)
{
// 移除当前选项
selectObj.options[0] = null;
}
}
function removeOptionsExcept(selectObj)
{
if (typeof selectObj != 'object')
{ selectObj = document.getElementById(selectObj); }
// 原有选项计数
var len = selectObj.options.length;
for (var i=0; i < len; i++)
{
// 移除当前选项
selectObj.options[0] = null;
}
selectObj.options[0]=new Option('-please select-','');
}
</script>
<form id="form1" runat="server">
<div>
<select id="province" onclick="if(this.value != ''){ setCity(this.options[this.selectedIndex].value);}else{noneSelected(city)}">
<option value="">-please select-</option>
<option value="Jiangsu">Jiangsu</option>
<option value="Shanghai">Shanghai</option>
</select>
<select id="city">
<option value="">-please select-</option>
</select>
</div>
</form>
很简单 3级4级一样搞