甜蜜警报 - 无法将成功甜蜜警报添加到简单表单提交

Sweet alert - unable to add success sweet alert to simple form submit

**

function bindSweetAlertButtonDemo() {
  const swalButton = document.getElementById('sweet-alert-demo');
  if (swalButton) { // protect other pages
    swalButton.addEventListener('click', () => {
      swal({
        title: "Nice",
        text: "You've added a task. Click on it for more details",
        icon: "success"

      });

 event.preventDefault()


    });
  }
}
<div>
  <%= simple_form_for [ @task] do |f| %>
   <%= f.input :name %>
   <%= f.input :description %>
   <%= f.submit :submit, class: "btn btn-danger" ,id: "sweet-alert-demo" %>
  <% end %>

</div>

我试图制作一个带有提交按钮的表单,以将任务添加到索引页。在提交时,我想要一个成功的甜蜜警报。然而,警报在几毫秒后首先消失,但通过 preventdefault() 解决了这个问题。但是现在提交实际上不再起作用了。有任何想法吗? (我已经正确导入了东西,只是没有在片段中添加它)

您需要定义event。如果用户单击 Ok,您可以使用 swal.then 提交表单。

swalButton.addEventListener('click', (event) => {
  swal({
    title: "Nice",
    text: "You've added a task. Click on it for more details",
    icon: "success"

  });
 event.preventDefault()
});

演示:

const swalButton = document.getElementById('sweet-alert-demo'), form = document.querySelector('form');
function bindSweetAlertButtonDemo() {
  if (swalButton) { // protect other pages
    swalButton.addEventListener('click', (event) => {
      swal({
        title: "Nice",
        text: "You've added a task. Click on it for more details",
        icon: "success"

      }).then(function(value){
        if(value!=null){
        form.submit();
        }
      });
        event.preventDefault();
    });
  }
}
bindSweetAlertButtonDemo();
<script src="https://unpkg.com/sweetalert@2.1.0/dist/sweetalert.min.js"></script>
<div>
<form>
<input type="text" name="name" placeholder="Name"><br/>
<input type="description" name="description" placeholder="Description"><br/>
<button id="sweet-alert-demo">Submit</button>
</form>
</div>