用动态数量的选择发出甜蜜的警报
Making a sweet alert with a dynamic amount of choices
我在一个项目中使用sweet alert让用户做出选择。然后在做出选择后,我使用 .then 中的 switch 语句执行我的代码。因此,例如,假设我们需要让用户 select 确认选项或取消选项。我知道怎么做:
swal( 'Are you sure you want to do this thing?', {
buttons: {
no: {
text: "No",
value: "cancel",
},
yes: {
text: "Yes",
value: "confirm",
},
},
})
.then ( (value) => {
switch (value) {
case 'confirm':
// do the confirm stuff here
break;
case 'cancel':
// do the cancel stuff here
break;
}
});
现在我运行遇到了问题。我有一个动态填充选择的数组,比如
let choices = [];
在项目的早期部分,可以将不同的字符串推送到此数组。我的问题是,如何调整上面的甜蜜警报代码以考虑任意数量的选择,然后为它们执行切换代码?
好吧,我找到了一个解决方案,我使用 HTML select 标签完成了它,然后使用可自定义的内容将其注入甜蜜警报:
let choices = document.createElement("select");
let names = ['nameOne', 'nameTwo', 'nameThree'];
names.forEach(name => {
let opt = document.createElement("option");
opt.appendChild(document.createTextNode(name));
opt.value = name;
choices.appendChild(opt);
});
swal('Testing', 'Choose an item', { content: choices })
.then( () => {
for (let item of choices) {
if (item.selected == true) {
// do stuff
}
}
});
请注意,这适用于任意长度的对象数组,因为我们使用 forEach 函数遍历数组中的所有项目并从中选择一个选项。
我在一个项目中使用sweet alert让用户做出选择。然后在做出选择后,我使用 .then 中的 switch 语句执行我的代码。因此,例如,假设我们需要让用户 select 确认选项或取消选项。我知道怎么做:
swal( 'Are you sure you want to do this thing?', {
buttons: {
no: {
text: "No",
value: "cancel",
},
yes: {
text: "Yes",
value: "confirm",
},
},
})
.then ( (value) => {
switch (value) {
case 'confirm':
// do the confirm stuff here
break;
case 'cancel':
// do the cancel stuff here
break;
}
});
现在我运行遇到了问题。我有一个动态填充选择的数组,比如
let choices = [];
在项目的早期部分,可以将不同的字符串推送到此数组。我的问题是,如何调整上面的甜蜜警报代码以考虑任意数量的选择,然后为它们执行切换代码?
好吧,我找到了一个解决方案,我使用 HTML select 标签完成了它,然后使用可自定义的内容将其注入甜蜜警报:
let choices = document.createElement("select");
let names = ['nameOne', 'nameTwo', 'nameThree'];
names.forEach(name => {
let opt = document.createElement("option");
opt.appendChild(document.createTextNode(name));
opt.value = name;
choices.appendChild(opt);
});
swal('Testing', 'Choose an item', { content: choices })
.then( () => {
for (let item of choices) {
if (item.selected == true) {
// do stuff
}
}
});
请注意,这适用于任意长度的对象数组,因为我们使用 forEach 函数遍历数组中的所有项目并从中选择一个选项。