我有一系列JSON数组,每个数组都包含对象,并且在.change函数中选择了其中一个数组,并且数组在if语句中。
var country_data;
$("#job").change(function () {
selectedValue = $("#job option:selected").val();
if (selectedValue == "job_1") {
country_data = [{
"country_id": 1,
"country": "Luxembourg",
"local_wage": "407",
"wage": "489",
"exchange": "0.98"
}, {
"country_id": 2,
"country": "Norway",
"local_wage": "3200",
"wage": "378",
"exchange": "9.57"
}, {
"country_id": 3,
"country": "Austria",
"local_wage": "290",
"wage": "337",
"exchange": "0.87"
}];
} else if (selectedValue == "job_2") {
country_data = [{
"country_id": 1,
"country": "Luxembourg",
"local_wage": "874",
"wage": "654",
"exchange": "0.24"
}, {
"country_id": 2,
"country": "Norway",
"local_wage": "741",
"wage": "365",
"exchange": "4.77"
}, {
"country_id": 3,
"country": "Austria",
"local_wage": "854",
"wage": "634",
"exchange": "0.43"
}];
} else if (selectedValue == "job_3") {
country_data = [{
"country_id": 1,
"country": "Luxembourg",
"local_wage": "854",
"wage": "985",
"exchange": "0.25"
}, {
"country_id": 2,
"country": "Norway",
"local_wage": "645",
"wage": "874",
"exchange": "5.55"
}, {
"country_id": 3,
"country": "Austria",
"local_wage": "201",
"wage": "256",
"exchange": "0.78"
}];
}
}).change();
我还有一个使用.each访问所选数组数据的函数,但我似乎无法访问所选JSON数组中的数据。
//variable country_data below wont access the selected array
$.each(country_data, function(i) {
var regEx = new RegExp('^' + searchStr + '\\w*\\b','i');
if (country_data[i].country.match(regEx) ||
(i == 3 && searchStr.toLowerCase() == "us") ||
(i == 4 && ((searchStr.toLowerCase() == "uk") ||
("Great Britain".match(regEx)) ||
("Britain".match(regEx)) ||
("England".match(regEx)) ||
("Wales".match(regEx)) ||
("Scotland".match(regEx)) ||
("Northern Ireland".match(regEx))
)
)
)
$suggestionList.append('<li class="country_result" role="option"><a href="#'+country_data[i].country_id+'">' + country_data[i].country + '</a></li>');
if (country_data[i].country.toLowerCase() === searchStr.toLowerCase()) {
exactMatch = true;
select_current_country(i+1);
return;
}
});
我收到错误&#39;无法读取属性&#39;长度&#39;未定义的&#39;。如何修改.each函数以便我可以访问对象数据?任何帮助真的很感激!感谢
答案 0 :(得分:0)
因为当脚本首先运行时,您的变量country_data将是未定义的。 不要使用ifelse - 使用开关。