我试图填充一个select(带有数组中的值),具体取决于他们从第一个下拉列表中选择的选项
我的函数中有数组,如下所示:
residential = ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
用户正在从下拉列表中进行选择,例如ID为“住宅”,我想用上面数组中的值填充第二个选择。
所以我抓住所选选项的ID,如下所示:
var org_cat = $(this).children(":selected").attr("id");
所以,org_cat的值例如是'residential',所以我想我可以尝试迭代这个,因为数组被称为'住宅'
所以我试图按如下方式遍历数组:
$.each(org_cat, function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
但是,变量'org_cat'不被视为数组。
我做错了什么,我是否必须以某种方式告诉JQuery它的数组?
这是我遇到的错误。
TypeError: invalid 'in' operand a
答案 0 :(得分:2)
您要做的是引用变量&#34;住宅&#34; (使用字符串)(即数组)。因此,你可以拥有一个像这样的对象:
var org_cat = $(this).children(":selected").attr("id"); // = "residential"
var obj =
{
"residential": ["R1_:_Single_Private_Dwelling","CH1_:_Self-Catering_Holiday_Unit","R2_:_Flats_or_Maisonettes_Up_to_3_floors_Purpose_Built","R3_:_Flats_or_Maisonettes_4_floors_and_over_Purpose_Built","CC7_:_Time_Share_Complex","R4_:_Houses_Converted_to_Flats_Up_to_2_Floors","R5_:_Houses_Converted_to_Flats_3_floors_and_over","MR_:_Hostel","R6_:_HMO","CC_:_Camping_Site","CC1_:_Caravan_Park","CC5_:_Chalet_Park","CC6_:_Caravan_And_Chalet_Park_","CC_:_Gypsy_Caravan_Site","XX1_:_Other"]; institutionalVal = ["MH2_:_Hospital","MH3_:_Hospital_(private)","MR1_:_(Care)_Home_for_older_people_(Over_65)","MR2_:_(Care)_home_for_adult_placements_"];
}
获得阵列&#34;住宅&#34;思想引用对象中的索引,如:
obj[org_cat]
所以在每个jQuery上:
$.each(obj[org_cat], function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});
或者如果您的变量&#34;住宅&#34;是全局的,您可以通过window[org_cat]
之类的窗口对象而不是obj[org_cat]