javascript - 从数组中创建一个新的选择选项
问题描述
我从 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);
}
我可以从控制台访问数组中的数据。
解决方案
我不知道我的代码有什么问题
那是因为这$.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();
});
}
推荐阅读
- javascript - 如果不期望返回,跨域 Ajax 调用是否需要代理?
- c# - 如何将 MIDI 从 Unity 发送到外部 VST
- java - Appium 框架中的非法参数异常
- git - 从文件中删除所有未跟踪
- html - CSS 正确:-50 并且过渡不起作用
- java - JavaFX 2 秒后在 GridPane 上添加行
- python - 错误:ImportError: cannot import name 'doSum' from 'Sum' (G:\firstpy\Sum.py)
- javascript - 意外的令牌 = import/no-named-as-default eslint 错误
- shell - 使用shell脚本awk将另一个字段上的函数结果附加到csv中
- python - 如何在 keras 神经网络中进行简单的数据召回