gpt4 book ai didi

javascript - Jquery - 使用 HTML :selected to fetch an array with the same name

转载 作者:搜寻专家 更新时间:2023-10-31 22:43:07 24 4
gpt4 key购买 nike

我的 HTML 中有这个选择输入

                <select class="" id="countries" name="Country">
<option value="AL">
Albania
</option>
<option value="HR">
Croatia
</option>
<option value="BG">
Bulgaria
</option>
<option value="MK">
Macedonia
</option>
<option value="MT">
Malta
</option>
<option value="MD">
Moldova
</option>
<option value="RO">
Romania
</option>
<option value="RS">
Serbia
</option>
<option value="SI">
Slovenia
</option>
</select>

在 Jquery 中,我有与此选择值同名的数组。数组中填充了不相关的数据。

var Albania = [];
var Croatia = [];
var Bulgaria= [];
...

根据选择的国家/地区,另一个选择输入应填充具有相同国家/地区名称的数组。另一个选择是 #cepsp

$( "#countries").change(function() {
$('#cepsp').empty();
var option = '';
for (var tt=0;tt<Albania.length;tt++)
{option += '<option value="'+Albania[tt]+'">'+Albania[tt]+'</option>';}
$('#cepsp').append(option);
});

请注意我是如何在 Jquery 中使用 Albania 数组的,它运行良好。但我也希望其他国家也这样做。我试过:

$( "#cepsp option:selected" ).text()[tt]

但这当然行不通。

如何将选定输入的文本传输到变量名称?

最佳答案

如果将数组结构更改为 an object thus :

var countriesArra ={
Albania:[],
Croatia:[],
Bulgaria:[],
....
}

您现在可以根据名称选择正确的数组:

$( "#countries").change(function() {
// get name that macthes array name, i.e. the text not the value
var countryName = $(this).text();
//countryName should be "Albania" not "AL"
$('#cepsp').empty();
var option = $('<option>');
for (var tt=0;tt<countriesArra[countryName].length;tt++)
{
//variable prevents querying the array twice, so this should be more efficent
var countryNameFromArra = countriesArra[countryName][tt];
option.val(countryNameFromArra).html(countryNameFromArra);
}
$('#cepsp').append(option);
});

这是有效的,因为你可以 access an object's properties by the string of the property name .

所以 countriesArra['Albania']返回“阿尔巴尼亚”数组。然后你迭代你的 tt在此数组上正常变量,例如countriesArra['Albania'][0]返回对象的阿尔巴尼亚数组中的第一项。

Brief fiddle

我还整理了您的选项创建。所以我使用 jquery var option = $('<option>'); 创建了一个“选项”对象.然后我可以访问它的方法和属性作为 jquery 对象,而不是字符串连接它。

option.val(countriesArra[countryName][tt]).html(countriesArra[countryName][tt]);

关于javascript - Jquery - 使用 HTML :selected to fetch an array with the same name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28833492/

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