javascript - 通过动态数量的选择发出甜蜜的警报
问题描述
我在项目中使用甜蜜警报供用户做出选择。然后在做出选择后,我使用 .then 中的 switch 语句执行我的代码。例如,假设我们需要让用户选择确认选项或取消选项。我知道该怎么做:
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 选择标签完成了它,然后使用可自定义的内容将其注入到甜蜜警报中:
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 函数循环遍历数组中的所有项目并从中选择一个选项。
推荐阅读
- python - 获取视图不会在我的烧瓶聊天机器人上返回有效的响应错误消息
- node.js - Sendgrid Node.js 错误:将循环结构转换为 JSON
- javascript - React Bootstrap:在页面重新加载时保留当前选项卡
- python - Python - Selenium Webdriver 查找所有 div 节点具有相似名称的元素
- php - php。拉拉维尔。多重依赖注入
- c++ - 两个函数,但只有第一个函数显示输出
- string - 如果字符串中小写字母的个数为偶数则递归返回
- azure - 天蓝色应用服务容器(容器名称)未响应端口上的 HTTP ping:8080
- controller - 保存依赖于两个表的记录
- python - 比较多个 Pandas DataFrame 的匹配值