如何在函数中使用for循环填充两个下拉菜单?

时间:2019-01-10 14:07:42

标签: javascript for-loop drop-down-menu

我正在尝试使用for循环制作两个包含相同货币列表的下拉菜单。我有这个对象:

var ECurrencyTypes = {
    NOK: {value:1.00000, name: "Norske kroner", denomination: "kr"},
    EUR: {value:0.10733, name: "Europeiske euro", denomination: "€"},
    USD: {value:0.12652, name: "United States dollar", denomination: "$"},
    GBP: {value:0.09550, name: "Pound sterling", denomination: "£"},
    INR: {value:8.18624, name: "Indiske rupee", denomination: "र"},
    AUD: {value:0.16129, name: "Australienske dollar", denomination: "A$"},
    PHP: {value:6.48595, name: "Filippinske peso", denomination: "₱"},
    SEK: {value:1.02580, name: "Svenske kroner", denomination: "kr"},
    CAD: {value:0.15841, name: "Canadiske dollar", denomination: "C$"},
    THB: {value:4.18410, name: "Thai baht", denomination: "฿"}
  };

我有一个包含两种形式的HTML页面。用户应该能够更改首选货币。在网络表单中,字段如下所示:

<select name="Valutatype" id="selectCurrencyType"></select>

 <select id="selectAccountCurrency"></select>

我要使用的功能如下:

function loadAllCurrencyKeys() {
  var keys = Object.keys(ECurrencyTypes);
  for (var index = 0; index < keys.length; index++) {
      var currencyKey = keys[index];
      var newOption = document.createElement("option");
      newOption.value = currencyKey;
      newOption.text = ECurrencyTypes[currencyKey].name;
      selectCurrencyType.options.add(newOption);          
  }
}

loadAllCurrencyKeys();

是否可以在同一函数中包含另一个包含 selectAccountCurrency 的for循环?

2 个答案:

答案 0 :(得分:1)

问题在以下声明中

 for (var index = 0; index = keys.lenght; index++) {

将其更改为

 for (var index = 0; index < keys.length; index++) {

答案 1 :(得分:1)

创建newOption并配置所有属性后,请尝试

document.querySelector("#selectAccountCurrency").appendChild(newOption)