我正在使用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。我需要填写表格并阻止提交吗?
答案 0 :(得分:2)
问题是点击锚元素具有默认行为。您可以使用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!");
}
});
}
答案 1 :(得分:0)
您可以像这样在href属性中添加值Viewencapsulation
javascript:
答案 2 :(得分:-1)
尝试从链接中删除href,并仅在用户单击SweetAlert脚本中的确认后处理链接。
<div class="delete"><a onclick="return confirmation()"><i class="far fa-trash-alt"></i></a></div>
在您的JavaScript中:
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) {
// TODO: Handle your delete url by ajax
// ...
swal("Poof! Your imaginary file has been deleted!", {
icon: "success",
});
} else {
swal("Your imaginary file is safe!");
}
});