首页 > 解决方案 > 从数组中创建一个新的选择选项

问题描述

我从 JSON 创建了数组,我想在我的选择中创建新选项。我没有任何错误,我不知道我的代码有什么问题。在 HTML 中,我有:

<select class="currencyList">
</select>

在 JS 中:

var currencyList = [];

    $(document).ready(function() {
      getCurrencies();
      createOptions();
    });

    function getCurrencies() {
      $.getJSON(
        "http://api.nbp.pl/api/exchangerates/tables/a/?format=json",
        function(response) {
          $.each(response[0].rates, function(i, item) {
            currencyList.push(item);
          });
        }
      );
    }

    function createOptions() {
      var option = "";
      for (var i = 0; i < currencyList.length; i++) {
        option += "<option value='" + currencyList[i].code + "'>" + currencyList[i].currency + "</option>";
      }
        $(".currencyList").append(option);
    }

我可以从控制台访问数组中的数据。

标签: javascriptjquery

解决方案


我不知道我的代码有什么问题

那是因为这$.getJSON是一个异步函数。

基本上,您在AJAXcreateOptions调用完成之前调用函数。$.getJSON

您需要附加done承诺回调函数。

function getCurrencies() {
  $.getJSON(
    "http://api.nbp.pl/api/exchangerates/tables/a/?format=json",
    function(response) {
      $.each(response[0].rates, function(i, item) {
        currencyList.push(item);
      });
    }
  ).done(function(){
       createOptions();
  });
}

推荐阅读