gpt4 book ai didi

javascript - JQuery 数组,通过变量访问?

转载 作者:行者123 更新时间:2023-12-02 13:49:21 25 4
gpt4 key购买 nike

我尝试根据他们从第一个下拉列表中选择的选项来填充选择(使用数组中的值)

我的函数中有数组,如下所示:

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”,所以我想我可以尝试迭代它,因为该数组称为“residential”

所以我尝试如下循环遍历数组:

$.each(org_cat, function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});

但是,变量“org_cat”没有被视为数组。

我做错了什么,我必须以某种方式告诉 JQuery 它是一个数组吗?

这是我遇到的错误。

TypeError: invalid 'in' operand a

最佳答案

您想要做的是使用字符串引用变量“residential”(即数组)。因此,您可以拥有一个像这样的对象:

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_"];
}

并获取数组“residential”,引用对象中的索引,例如:

obj[org_cat]

所以在 jQuery 上:

$.each(obj[org_cat], function(value) {
$('#area_usage')
.append($("<option></option>")
.attr("value", value)
.text(value));
});

或者,如果您的变量“residential”是全局变量,您可以通过窗口对象引用它,例如 window[org_cat] 而不是 obj[org_cat]

关于javascript - JQuery 数组,通过变量访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com