我正在制作一个下拉菜单,我需要在一个选择标记中显示省份和城市。
因此,在加载时,它将显示所有省份,当我选择一个省时,列表将更改为城市。
我能够显示省份列表,但我不知道如何显示城市。
我希望你理解我。
感谢。
示例代码
var province=[ {
"id": "820000",
"name": "澳门",
"city": [ {
"id": "820001", "name": "澳门"
}
]
}
$(document).ready(function () {
var provinceListItems = '<option selected="selected" value="">省</option>';
var citiesListItems = '<option selected="selected" value="">城市</option>';
for (var i = 0; i < province.length; i++) {
provinceListItems += "<option value='" + province[i].name + "'>" + province[i].name + "</option>";
}
$("#provinceCity").html(provinceListItems);
});
答案 0 :(得分:1)
var province=[
{
"id": "820000",
"name": "P1",
"city": [
{
"id": "820001", "name": "C1P1"
},
{
"id": "820002", "name": "C2P1"
},
{
"id": "820003", "name": "C3P1"
}
]
},
{
"id": "830000",
"name": "P2",
"city": [
{
"id": "830001", "name": "C1P2"
},
{
"id": "830002", "name": "C2P2"
},
{
"id": "830003", "name": "C3P2"
}
]
}
];
function loadProvince(){
$("#provinceCity").html("<option value=''>Select province</option>");
for (var i=0; i<province.length; i++){
$("#provinceCity").append("<option value='"+province[i]["id"]+"'>"+province[i]["name"]+"</option>");
}
}
$(document).ready(function(){
$("#clearBtn").hide();
loadProvince();
$("#clearBtn").click(function(){
loadProvince();
});
$("#provinceCity").change(function(){
for (var i=0; i<province.length; i++){
if ($(this).val() == province[i]["id"]){
$("#clearBtn").show();
$("#provinceCity").empty();
var cities = province[i]["city"];
for (var j=0; j<cities.length; j++){
$("#provinceCity").append("<option value='"+cities[j]["id"]+"'>"+cities[j]["name"]+"</option>");
}
}
}
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="provinceCity">
<option value=''>Select province</option>
</select> <button id="clearBtn">Clear</button>
&#13;