防止链接,确认然后获得位置jQuery
-
26-10-2019 - |
题
我有这样的链接。
<a href="delete.php?id=1" class="delete">Delete</a>
如果用户单击它。确认应弹出,然后只有在用户单击“是”时,它应该得到实际的URL。
我知道这可以防止默认行为
function show_confirm()
{
var r=confirm("Are you sure you want to delete?");
if (r==true) { **//what to do here?!!** }
}
$('.delete').click(function(event) {
event.preventDefault();
show_confirm()
});
但是,确认后如何继续该链接或将AJAX帖子发送到该链接?
解决方案
您可以在单击中完成所有操作:
$('.delete').click(function(event) {
event.preventDefault();
var r=confirm("Are you sure you want to delete?");
if (r==true) {
window.location = $(this).attr('href');
}
});
或者,您可以通过将单击元素传递到该函数来做到这一点:
function show_confirm(obj){
var r=confirm("Are you sure you want to delete?");
if (r==true)
window.location = obj.attr('href');
}
$('.delete').click(function(event) {
event.preventDefault();
show_confirm($(this));
});
其他提示
我花了一段时间才弄清楚这一点,所以我认为我会发布解决方案。
$('.delete').click(function(e){
if(confirm('Are you sure?')){
// The user pressed OK
// Do nothing, the link will continue to be opened normally
} else {
// The user pressed Cancel, so prevent the link from opening
e.preventDefault();
}
}
我正在考虑以错误的方式确认。确认将阻止网站自动打开,并等待用户的输入。因此,基本上,您需要将预防违规移至其他。
因此,只有在单击取消时,您才能防止链接打开。这还允许链接像通常一样运行,例如,如果它具有目标=“ _ black”指令。
function show_confirm(url){
var r=confirm("Are you sure you want to delete?");
if (r==true){
location.top.href = url;
}
}
$('.delete').click(function(event) {
event.preventDefault();
show_confirm($(this).attr('href'));
});
如果您想使用Ajax,则可以替换 location.top.href = url;
和 $.get(url);
function show_confirm(elem)
{
var r=confirm("Are you sure you want to delete?");
if (r==true) {
window.location.href = elem.href;
}
}
$('.delete').click(function(event) {
event.preventDefault();
show_confirm(this)
});
这是一个简短的形式:
$('.delete').click(function(){return confirm("Are you sure you want to delete?")});
我在网站上使用它进行下载/链接确认。
要优化函数show_confirm中的代码,请尝试使用以下:
function show_confirm(obj){
if(confirm("Are you sure you want to delete?")) window.location = obj.attr('href');
}
你可以做
function show_confirm()
{
if(confirm("Are you sure you want to delete?")){
//make ajax call
}else{
//no ajax call
}
}
$('.delete').click(function() {
if (confirm('Are you sure?')) {
$.post($(this).attr('href'), function() {
// Delete is OK, update the table or whatever has to be done after a succesfull delete
....
}
}
return false;
}
不隶属于 StackOverflow