省份与城市对应选择的功能javascript

    技术2024-12-14  17

    网页内的代码:

    <body οnlοad="loadprovince()"> <select id="province" οnchange="cityitems()"> <option value="none">请选择省</option> </select> <select id="city"></select> </body>

    javascript代码:

    oSelect.options.add(new Option('显示', '真值', true, true));

    var datas = { "河北": ["石家庄", "唐山", "衡水"], "山东": ["济南", "烟台", "滨州"], "广东": ["广州", "深圳", "汕头"] }; function loadProvince() { var province = document.getElementById("province"); for (var key in datas) { var option = document.createElement("<option value=''></option>");//创建省份的选项 option.value = key; option.innerText = key; province.appendChild(option);//在遍历过程中逐一添加省份的选项中 } } function showcities() { var province = document.getElementById("province"); var city = document.getElementById("city"); var currentprovine = province.value;//获取当前选中的省份 var currentcities = datas[currentprovine]; //获取选中省份对应的城市数组 //方法一:先去掉城市列表中的值然后再增加新内容 //city.options.length = 0; //方法二:先去掉城市列表中的值然后再增加新内容,对数组要进行倒着删除从而避免了方法三的问题 for (var i = city.childNodes.length-1; i >= 0; i--) { city.removeChild(city.childNodes[i]); } /*方法三:由于数据的排序问题会删不干净 for (var i = 0; i < city.childNodes.length; i++) { city.removeChild(city.childNodes[i]); } */ for (var i = 0; i < currentcities.length; i++) { var currentcity = currentcities[i]; var option = document.createElement("<option value=''></option>"); //创建城市的选项 option.value = currentcity; option.innerText = currentcity; city.appendChild(option); //在遍历过程中逐一添加到城市的选项中 } }

    另外一种利用class的方法去掉city中的项:

      var province = document.getElementById("province"); var city = document.getElementById("city"); //city.options.length = 0; //简单的清除方式 /*移除节点法 for (var i = city.childNodes.length - 1; i >= 0; i--) { city.removeChild(city.childNodes[i]); } */ var cityoptions = city.getElementsByTagName("option"); for (var i = cityoptions.length - 1; i >= 0; i--) { if (cityoptions[i].className == "citystyle") { city.removeChild(cityoptions[i]); } } var currentpe = province.value; //当前的省份 var citys = datas[currentpe]; //省份对应的城市 if (currentpe == "none") { return; } for (var i = 0; i < citys.length; i++) { var option = document.createElement("<option value='' class='citystyle'></option>"); option.value = citys[i]; option.innerText = citys[i]; city.appendChild(option); }

    jquery版:

    var datas = { "河北省": ["衡水", "保定", "石家庄"], "山东省": ["滨州", "济南", "青岛"], "广东省": ["广州", "深圳", "汕头"] }; $(function () { $.each(datas, function (key, value) { var option = $("<option value=" + key + ">" + key + "</option>"); $("#province").append(option); }); $("#province").change(function () { var selectprovine = $("#province").val(); //获取当前省份 $("#city option").remove(); //清空city列表 if (selectprovine == "none") { return; } $(datas[selectprovine]).each(function () { var cityoption = $("<option value=" + this + ">" + this + "</option>"); $("#city").append(cityoption); }); }); });

     网页布局:

    <select id="province"> <option value="none">请选择</option> </select> <select id="city"></select>

    最新回复(0)