问题描述
我目前正在使用sweetalert2从对话框中捕获用户的输入.我想在链接队列对话框中使用下拉列表,但似乎找不到在下拉列表中动态添加项目的方法.假设我要从JSON格式检索数据并将其放在下拉列表中,有没有办法做到这一点?
I am currently using sweetalert2 to capture user's input from the dialog. I would like to use the dropdown in chaining queue dialog but I can't seem to find a way to dynamically add items in the dropdown list. Let's say I want to retrieve data from JSON format and place in the dropdown list, is there a way to do it?
function userInput() {
swal.setDefaults(
{
showLoaderOnConfirm: true,
confirmButtonText: 'Next →',
showCancelButton: true,
animation: true,
progressSteps: ['1', '2', '3']
}
);
var steps = [
{
text: 'Select an author to analyze the commit',
input: 'select',
inputOptions: {
'SRB': 'Serbia', // How do I dynamically set value?
'UKR': 'Ukraine',
'HRV': 'Croatia'
}
},
{
text: 'Select multiple authors to compare their commits',
input: 'select',
inputOptions: {
'SRB': 'Serbia', // How do I dynamically set value?
'UKR': 'Ukraine',
'HRV': 'Croatia'
}
},
{
text: 'Select a file directory to analyze all author\'s commit',
input: 'select',
inputOptions: {
'SRB': 'Serbia', // How do I dynamically set value?
'UKR': 'Ukraine',
'HRV': 'Croatia'
}
}
];
swal.queue(steps).then(function(result) {
swal.resetDefaults();
swal({
type: 'success',
title: 'Success',
text: 'Scroll down for statistics!',
html:
'Your selections: <pre>' +
JSON.stringify(result) +
'</pre>',
confirmButtonText: 'Ok',
showCancelButton: false
})
}, function() {
swal.resetDefaults()
})
}
以JSON格式检索数据:
Retrieve data in JSON format:
function getData(repolink) {
readDataFromGit('https://api.github.com/repos/' + repolink + '/git/trees/master?recursive=1', function(text){
data = JSON.parse(text);
$.each(data, function(i, v) {
// Retrieve v.login data!
data = v.login;
})
});
}
function readDataFromGit(link, callback) {
var request = new XMLHttpRequest();
request.overrideMimeType("application/json");
request.open('GET', link, true);
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == "200") {
callback(request.responseText);
}
};
request.send(null);
}
推荐答案
作为 SweetAlert2文档表示,inputOptions
参数可以是object
或Promise
.
As the SweetAlert2 documentation says, inputOptions
parameter can be object
or Promise
.
要动态填充选择的项目,您应该使用promise,这是简单的示例:
To populate select items dynamically you should use promises, here's the simple example:
var inputOptionsPromise = new Promise(function (resolve) {
// get your data and pass it to resolve()
setTimeout(function () {
resolve({
'#FF0000': 'Red',
'#00FF00': 'Green',
'#0000FF': 'Blue'
})
}, 2000)
})
swal({
input: 'select',
inputOptions: inputOptionsPromise
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@7"></script>
请注意,SweetAlert2将自动显示加载程序,直到解析或拒绝inputOptions
的Promise参数为止.
Notice, that SweetAlert2 will automatically show a loader until the Promise for inputOptions
parameter will be resolved or rejected.
这篇关于SweetAlert下拉列表可动态添加列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!