用变量替换对象文字的属性

时间:2015-02-02 12:56:26

标签: javascript

我有一个对象文字,其中包含两个值,价格和名称的国家/地区列表: enter image description here

当选择更改时,我存储当前所选国家/地区的值: enter image description here

我将此值存储在变量内部函数.change():

current_country = $('#country').val();

我以这种方式访问​​了对象文字,例如countries_list.deu

但是当我使用current_country时,变量控制台会显示未定义的内容:

 console.log(countries_list.current_country);

我如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

使用 selectedIndex 获取所选的值索引并使用 .options [i] .value 获取具有以下索引的选项的值:

var countries = document.getElementById("country");
var current_country = countries.options[countries.selectedIndex].value;

答案 1 :(得分:0)

你应该使用括号表示法

console.log(countries_list[current_country]);

在您的情况下,它实际上在对象中查找名为current_country的属性,它不存在。

请查看this以更好地理解两种不同的符号

相关问题