简体   繁体   English

通过动态数量的选择发出甜蜜警报

[英]Making a sweet alert with a dynamic amount of choices

I am using sweet alert in a project for the user to make choices.我在一个项目中使用甜蜜警报让用户做出选择。 Then after a choice is made, I execute my code using switch statement inside of .then.然后在做出选择后,我使用 .then 中的 switch 语句执行我的代码。 So for instance, say we need to have the user select a confirm option or a cancel option.例如,假设我们需要让用户选择确认选项或取消选项。 I know how to do this:我知道如何做到这一点:

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;
    }
  });

Now I run into a problem.现在我遇到了一个问题。 I have an array that is dynamically filled with choices, say我有一个动态填充选择的数组,比如

let choices = [];

and at earlier parts in the project, different strings can be pushed to this array.在项目的早期部分,可以将不同的字符串推送到此数组。 My question is, how do I adjust my sweet alert code above to account for an arbitrary amount of choices and then executing the switch code for them?我的问题是,如何调整上面的甜蜜警报代码以考虑任意数量的选择,然后为它们执行切换代码?

Well I have found a solution, and I have done it using HTML select tag and then injecting that into sweet alert using customizable content:好吧,我找到了一个解决方案,我已经使用 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
    }
   }
 });

Note that this will work for any arbitrarily long array of objects, since we use the forEach function to loop through all items in the array and make an option out of them.请注意,这适用于任何任意长的对象数组,因为我们使用 forEach 函数循环遍历数组中的所有项目并从中选择一个选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM