javascript - 带有 href 的 Sweet Alert 删除确认

标签 javascript php sweetalert

我正在使用 PHP,并使用 Sweet alert 进行删除确认。问题是它在显示甜蜜警报之前正在删除。

这是我的 HTML(其中使用了 PHP)。

<div class="delete"><a onclick="return confirmation()" href="'.URLROOT.'/dashboards/delete_note/'.htmlspecialchars($note->note_id).'/'.$data['table'] .'"><i class="far fa-trash-alt"></i></a></div>

这是我的甜蜜提醒

function confirmation() {
swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this imaginary file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
    swal("Poof! Your imaginary file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your imaginary file is safe!");
  }
});

问题是,它没有显示甜蜜警报,它只是直接转到 URL。我是否需要做一个表格并防止提交或类似的东西?

最佳答案

问题是点击 anchor 元素有一个默认行为。您可以使用 event.preventDefault() 来阻止重定向,并根据您使用 window.location.href='url'

的逻辑手动导航
<div class="delete">
   <a onclick="confirmation(event)" href="'.URLROOT.'/dashboards/delete_note/'.htmlspecialchars($note->note_id).'/'.$data['table'] .'">
     <i class="far fa-trash-alt"></i>
  </a>
</div>

在 js 中

function confirmation(ev) {
ev.preventDefault();
var urlToRedirect = ev.currentTarget.getAttribute('href'); //use currentTarget because the click may be on the nested i tag and not a tag causing the href to be empty
console.log(urlToRedirect); // verify if this is the right URL
swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this imaginary file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  // redirect with javascript here as per your logic after showing the alert using the urlToRedirect value
  if (willDelete) {
    swal("Poof! Your imaginary file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your imaginary file is safe!");
  }
});
}

关于javascript - 带有 href 的 Sweet Alert 删除确认,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54603673/

相关文章:

php - MySQL 只插入第一个字符

php - javascript 页面重新加载后保留值

php - 有没有办法制作 "Undetectable Iframe Code"

javascript - 甜蜜警报确认然后将数据保存到数据库

javascript - 如何让进度条与 jQuery 的 AJAX 函数一起使用?

javascript - 使用redux打开状态时Material-ui对话框闪烁

javascript - 有没有更好的显示和隐藏方式?

javascript - Polymer 2.0 基本 dom-repeat 列表示例不起作用

JavaScript SweetAlert 不工作?

javascript - 无法使用甜蜜警报单击“确定”