📜  sweet alert 2 对确认执行操作 - Javascript (1)

📅  最后修改于: 2023-12-03 15:05:25.520000             🧑  作者: Mango

Sweet Alert 2

Sweet Alert 2 is a JavaScript library that provides beautiful, customizable, and easy-to-use alerts, prompts, and confirmations. It is a great alternative to the default browser dialogs and offers a much better user experience.

Installation

The easiest way to install Sweet Alert 2 is via npm:

npm install sweetalert2

Alternatively, you can include it directly in your HTML file:

<script src="//cdn.jsdelivr.net/npm/sweetalert2@10"></script>
Usage

Alerts

You can use the Swal.fire() function to display a simple alert:

Swal.fire('Hello World!')

This will display a dialog box with the message "Hello World!".

Confirmations

Sweet Alert 2 can be used to display confirmation dialogs before executing an action:

Swal.fire({
  title: 'Are you sure?',
  text: "You won't be able to revert this!",
  icon: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.isConfirmed) {
    // Code to execute if user confirms
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})

This code will display a dialog box with the title "Are you sure?", a warning icon, and a message asking the user if they really want to delete something. The "Cancel" and "Yes, delete it!" buttons will be displayed, and if the user clicks the latter one, a success message will be shown.

Advanced customization

Sweet Alert 2 offers a lot of customization options, ranging from changing the icon and button colors to adding custom HTML content and animations. You can find all the available options in the official documentation.

Conclusion

Sweet Alert 2 is a great library for displaying alerts and confirmations in your JavaScript applications. Its ease of use, flexibility, and configurability make it a valuable tool for enhancing the user experience and making your application more professional.