<form action="#" name="myform"> <label>省</label><select name="provice" id="provice"><option value="-1">请输入省份</option></select> <label>市</label><select name="city" id="city"><option value="-1">请输入城市</option></select> <label>县</label><select name="locale" id="locale"><option value="-1">请输入区县</option></select> </form>
2. 定义json数据源:
var jsonData = [{ treeNode : '请输入省份', value : -1, childNode : [{ treeNode : '请输入城市', value : -1, childNode : [{ treeNode : '请输入区县', value : -1, childNode : [] }] }] },{ treeNode : '北京', value : 1, childNode : [{ treeNode : '东城区', value : 11, childNode : [] },{ treeNode : '西城区', value : 12, childNode : [] }] },{ treeNode : '广西壮族自治区', value : 2601, childNode : [{ treeNode : '南宁', value : 6653, childNode : [{ treeNode : '横县', value : 10799, childNode : [] }, { treeNode : '宾阳县', value : 10800, childNode : [] }] }] }]
3. javascript代码:
function initCountry(){ var provice = $("#provice"); var city = $("#city"); var locale = $("#locale"); var proviceStr = ""; $.each(<span style="color:#FF0000;">jsonData</span>,function(index,items){ proviceStr += "<option value='"+jsonData[index].value+"'>"+jsonData[index].treeNode+"</option>"; }); provice.empty().append(proviceStr); provice.bind("change",function(){ if($(this).find(":selected").attr("value") == -1){ city.empty().append("<option value='-1'>请输入区县</option>"); } }); provice.bind("change",function(){ var cityStr = ''; var index = provice.find(":selected").index(); $.each(jsonData[index].childNode,function(index,items){ city.empty(); cityStr += "<option value='"+items.value+"'>"+items.treeNode+"</option>"; city.append(cityStr); }) changeLocale(); }); city.bind("change",changeLocale); function changeLocale(){ var localeStr = ''; var index = provice.find(":selected").index(); var index2 = city.find(":selected").index(); $.each(jsonData[index].childNode[index2].childNode,function(index,items){ locale.empty(); localeStr += "<option value='"+items.value+"'>"+items.treeNode+"</option>"; locale.append(localeStr); }) if(localeStr == ''){ locale.empty(); locale.append("<option value='-11'>请输入区县</option>"); } } } $(function(){ initCountry(); })