我正在为国家,州和城市建立一个依赖的下拉列表。它进展不顺利。我过去几天在Stackoverflow和网络上的其他网站上对这个主题进行了广泛的研究,并且无法获得#状态'选择对象以根据所选的'#country'来填充状态。选择从json填充国家的对象就好了。在根据“变更”选择国家/地区后,各州都没有填写。方法。我有一个' if'声明,如果所选#country ===' US' (显示为北美),然后加载美国州和地区.json文件。
在摆弄代码之后,我终于得到了#状态'下拉至至少显示对象[对象]',所以我知道我越来越接近解决方案了。我不太清楚为什么它显示对象[对象]'在州下拉列表中。它可能是一种类型'某种错误,其中json被显示为一个对象而不是一个字符串,但我不明白如何在我的代码的上下文中解决这个问题。
非常感谢任何帮助。
以下是HTML:
<!doctype html>
<html>
<head>
<title>Country->State->City</title>
</head>
<body>
Country:
<select id="country">
<pre><option selected value="base">Select Country</option><pre>
</select>
State:
<select id="state">
<option selected value="base">Select state</option>
</select>
City:
<select id="city">
<option selected value="base">Select City</option>
</select>
<script type = "text/javascript" src="jquery-2.2.4.min.js"></script>
<script type = "text/javascript" src="custom.js"></script>
</body>
</html>
的jQuery
$(function(){
let countryOptions;
let stateOptions;
let gaCitiesOps;
$.getJSON('countries.json',function(data){
$.each(data, function(i,country) {
countryOptions+=
'<option value= "'+country.code+'">'
+country.name+
'</option>';
});
$('#country').html(countryOptions);
});
$("#country").change(function(){
if($(this).val()==="US"){
$.getJSON('us_states.json',function(data){
$.each(data, function(stateCode,stateName) {
stateOptions+='<option value="'+stateCode+'">'
+stateName+
'</option>';
});
$('#state').html(stateOptions);
});
}
});
$("#state").change(function(){
if($(this).val()==="GA"){
$.getJSON('GA_cities.json',function(data){
$.each(data, function(statecode,city) {
gaCitiesOps +='<option value="'+statecode+'">'
+city+
'</option>';
});
$('#city').html(gaCitiesOps);
});
}
});
});
Countries.json
[
{
"code": "US",
"name": "North America"
},
{
"code": "AG",
"name": "Antigua"
},
{
"code": "AU",
"name": "Australia"
},
{
"code": "AT",
"name": "Austria"
},
{
"code": "BG" ,
"name": "Bulgaria"
},
{
"code": "CA",
"name": "Canada"
},
.....ect
us_states.json
[
{
"stateCode": "AL",
"name": "Alabama"
},
{
"stateCode": "AR",
"name": "Arkansas"
},
{
"stateCode": "AS",
"name": "American Samoa"
},
{
"stateCode": "AZ",
"name": "Arizona"
},
{
"stateCode": "CA",
"name": "California"
},
.....etc
GA_cities.json
[
{
"code": "ALB",
"name": "ALBANY"
},
{
"code": "AMR",
"name": "AMERICUS"
},
{
"code": "ATH",
"name": "ATHENS"
},
{
"code": "ATL",
"name": "ATLANTA"
},
{
"code": "AUG",
"name": "AUGUSTA"
},
{
"code": "BAI",
"name": "BAINBRIDGE"
},
....etc
感谢您的考虑!
答案 0 :(得分:2)
console.log()
是你最好的朋友。尝试记录从$.each
获得的值,您就会知道为什么会得到[object Object]
。
$.each(data, function(stateCode, stateName));
输出为stateCode 0, stateName {stateCode: "AL", name: "Alabama"}
$.each
参数是(键,值),并且您循环遍历数组,因此键(在本例中为stateCode)是数组的索引。
ES6;如果你想要花哨,你可以将论点解构为
$.each(key, {stateCode, name});