希望有人能帮助我。下面的 JS 加载 JSON 文件并将县解析为选择菜单。它还会删除重复项。现在,在 JSON feed 中,每个项目都有这样的内容:
{
"County":"Antrim",
"Town":"Antrim Town",
"Restaurant":"Diane's Restaurant & Pizzeria"
}
我想做的是在第一个选择菜单中,一旦用户选择了县,第二个选择菜单就会使用子对象中的值进行更新。目前我收到“找不到变量”错误,但我不知道原因。数据数组是否由于某种原因不可用?
<script type="text/JavaScript">
$(document).ready(function(){
//get a reference to the select elements
var county = $('#county');
var town = $('#town');
var restaurant = $('#restaurant');
//request the JSON data and parse into the select element
$.getJSON('rai.json', function(data){
console.log(data);
//clear the current content of the select
$('#county').html('');
$('#county').append('<option>Please select county</option>');
$('#county').html('');
$('#town').append('<option>Please select town</option>');
$('#restaurant').html('');
$('#restaurant').append('<option>Please select restaurant</option>');
//iterate over the data and append a select option
$.each(data.irishtowns, function(key, val) {
county.append('<option id="' + val.County + '">' + val.County+ '</option>');
});
var a = new Array();
$('#county').children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
});
$( "#county" ).change(function() {
var myCounty = $(this).val();
console.log(myCounty);
$.each(data.irishtowns, function(key, val) {
if (val.Town === myCounty) {
town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
}
});
});
});
</script>
最佳答案
数据不在本行范围内
$.each(data.irishtowns, function(key, val) {
您可以将其移至回调中,或使用全局变量来提供访问:即在回调中包含一行 countries = data
,然后是
$.each(countries.irishtowns, function(key, val) {
关于javascript - 尝试访问 json 对象时出现 'Cannot find variable' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34682776/