我需要将我的sweetalert1 JS插件迁移到Sweetalert2插件。

但是,我完全不知道如何迁移以下代码:

swal("A wild Pikachu appeared! What do you want to do?", {
  buttons: {
    cancel: "Run away!",
    catch: {
      text: "Throw Pokéball!",
      value: "catch",
    },
    defeat: true,
  },
})
.then((value) => {
  switch (value) {

    case "defeat":
      swal("Pikachu fainted! You gained 500 XP!");
      break;

    case "catch":
      swal("Gotcha!", "Pikachu was caught!", "success");
      break;

    default:
      swal("Got away safely!");
  }
});


sweetalert1:https://sweetalert.js.org/guides/#advanced-examples

sweetalert2:https://sweetalert2.github.io/

对将代码格式化为sweetalert2有帮助吗?

最佳答案

首先,SweetAlert2默认情况下不允许超过2个按钮,但是您可以通过使用带有jQuery绑定as described in this question的自定义HTML按钮来完成相同的操作。对于您的特定问题,结果应大致如下所示:



    $(document).on('click', '.SwalBtn1', function() {
        //Some code 1
        console.log('Button 1');
        swal.clickConfirm();
        swal("Got away safely!");
    });
    $(document).on('click', '.SwalBtn2', function() {
        //Some code 2
        console.log('Button 2');
        swal.clickConfirm();
        swal("Gotcha!", "Pikachu was caught!", "success");
    });
    $(document).on('click', '.SwalBtn3', function() {
        // Some code 3
        console.log('Button 3');
        swal.clickConfirm();
        swal("Pikachu fainted! You gained 500 XP!");
    });

    swal({
        title: 'Oh oh!',
        html: "<p>A wild Pikachu appeared! What do you want to do?</p>" +
            '<button class="SwalBtn1 swal2-custom-button swal2-styled">' + 'Run Away!' + '</button>' +
            '<button class="SwalBtn2 swal2-custom-button swal2-styled">' + 'Throw Pokéball!' + '</button>' +
            '<button class="SwalBtn3 swal2-custom-button swal2-styled">' + 'Defeat!' + '</button>',
        showCancelButton: false,
        showConfirmButton: false
    });

.swal2-custom-button {
  background-color: #3085d6;
  color: #fff;
  border: 0;
  border-radius: .2em;
}

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





SweetAlert2存储库上有一个documentation page,它为迁移其余组件提供了更好的解释(很酷的示例!)。但这应该使您走上需要做的事情。

关于javascript - sweetalert1 JS插件迁移到Sweealert2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51311735/

10-16 17:59