使用json填充选择器不能按预期工作
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用json填充选择器不能按预期工作相关的知识,希望对你有一定的参考价值。
我正在尝试使用JSON填充两个选择器。一个用于州,一个用于城市。如果我选择一个州,下一个选择器应该向我显示处于该州的城市。到目前为止,我已经使用了函数。我的状态功能正常,但是我的城市选择器遇到了麻烦。它没有显示任何东西。我被困在这里
在我的scripts.js中我有
function populateState(data){
var listState = "";
for(var i in data.states){
listState += '<option value="'+data.states[i].id+'">'+data.states[i].name+'</option>';
}
$('#states').html(listState);
}
function populateCities(data){
var listobj = "";
for(var i in data.states.cities){
listobj += '<option value="'+data.states.cities[i].id+'">'+data.states.cities[i].name+'</option>';
}
$('#cities').html(listobj);
}
在我的ready.js中,我使用了我的功能
var dataJson = {
"states": [
{
"name": "First state",
"id": "1",
"cities": [
{
"name": "city1",
"id": "cos"
},
{
"name": "city2",
"id": "mio"
},
{
"name": "city3",
"id": "top"
}
]
},
{
"name": "Second state",
"id": "2",
"cities": [
{
"name": "city4",
"id": "or"
},
{
"name": "city5",
"id": "st"
},
{
"name": "city6",
"id": "bs"
}
]
},
]
};
$(document).ready(function() {
populateState(dataJson);
$("#states").change(function () {
populateCities(dataJson);
});
});
这是HTML
<select id="states" >
<option value="000">-Select State-</option>
</select>
<select id="cities" >
<option value="000">-Select Cities-</option>
</select>
答案
问题是你不能用for(var i in data.states.cities){...}
迭代这样的城市。您需要遍历属于所选州的城市。
这是一个有效的例子。
function populateState(data){
var listState = "";
for(var i in data.states){
listState += '<option value="'+data.states[i].id+'">'+data.states[i].name+'</option>';
}
$('#states').html(listState);
}
function populateCities(data){
var listobj = "";
for(var i in data.states){
if (data.states[i].id == $("#states").val()) {
//this is the selected state, let's get their cities
for(var j in data.states[i].cities){
listobj += '<option value="'+data.states[i].cities[j].id+'">'+data.states[i].cities[j].name+'</option>';
}
}
}
$('#cities').html(listobj);
}
var dataJson = {
"states": [
{
"name": "First state",
"id": "1",
"cities": [
{
"name": "city1",
"id": "cos"
},
{
"name": "city2",
"id": "mio"
},
{
"name": "city3",
"id": "top"
}
]
},
{
"name": "Second state",
"id": "2",
"cities": [
{
"name": "city4",
"id": "or"
},
{
"name": "city5",
"id": "st"
},
{
"name": "city6",
"id": "bs"
}
]
},
]
};
$(document).ready(function() {
populateState(dataJson);
$("#states").change(function () {
populateCities(dataJson);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<select id="states" >
<option value="000">-Select State-</option>
</select>
<select id="cities" >
<option value="000">-Select Cities-</option>
</select>
以上是关于使用json填充选择器不能按预期工作的主要内容,如果未能解决你的问题,请参考以下文章