javascript - 带有 href 的 Sweet Alert 删除确认
问题描述
我使用 PHP 和 Sweet 警报来确认删除。问题是它在显示甜蜜警报之前正在删除。
这是我的 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。我需要做一个表格并防止提交或类似的东西吗?
解决方案
问题是单击锚元素具有默认行为。您可以使用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!");
}
});
}
推荐阅读
- laravel - 在 Eloquent 中默认忽略具有特定值的列
- java - Java - 修改复制的数组也会影响原始数组
- java - 如何在java中垂直循环遍历二维数组
- python-3.x - Folium choropleth 根本不给邮政编码区域着色
- java - 特殊字符检查,如果语句不起作用。爪哇
- django - Django 检索 CRSF 令牌
- swift - 更新 ObservableObject 值会关闭视图
- google-api - google 的 DCM api 中的什么会给我返回字段的数据类型?
- javascript - React-Bootstrap 不适用于组件
- rust - 为什么在字节数组上使用 AsciiString::from_ascii 时出现错误“索引处的字节不是 ASCII”?