2011-07-25 37 views
17

我有這樣的鏈接。防止鏈接,確認,然後轉到位置jquery

<a href="delete.php?id=1" class="delete">Delete</a> 

如果用戶點擊它。確認應該彈出,然後只有當用戶點擊是,它應該轉到實際的網址。

我知道,這樣可以防止默認行爲

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後該鏈接?

回答

29

你可以做這一切的內點擊:

$('.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)); 

}); 
+4

好了,所以..有一個陷阱,以這種方式,這將是如果用戶打算在新選項卡中打開鏈接,則不會查看該用戶是否打開了該鏈接,甚至可能有一個目標=「_ somespecificwindow」或target =「_ blank」.. :) –

+0

如果您在新tab_中打開或中間鼠標點擊鏈接,你會通過確認,使用'

2
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);

2
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) 
}); 
0
$('.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; 

} 
1

這是一個簡短的形式:

$('.delete').click(function(){return confirm("Are you sure you want to delete?")}); 

我用它在網站上下載/鏈接確認。

1

要優化功能show_confirm代碼,嘗試使用以下:

function show_confirm(obj){ 
    if(confirm("Are you sure you want to delete?")) window.location = obj.attr('href'); 
} 
3

我花了一段時間來想出解決辦法,所以我想我會後我的解決方案。

$('.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(); 
    } 
} 

我在考慮確認錯誤的方法。確認將阻止網站自動打開,並等待用戶的輸入。所以基本上,您需要將您的preventDefault移動到其他位置。

因此,只有當他們單擊取消時,您才阻止打開鏈接。這也允許鏈接正常工作,例如,如果它有一個target =「_ blank」指令。

+0

這一個爲我工作。如果我使用接受的解決方案'$(this).attr('href')'返回undefined' – dbr

0

如果你喜歡用警報/確認,這是最好的方法(我更喜歡使用Bootstrap Confirmationbootbox):

$('.confirm-delete').click(function(event) { 
    if (!confirm('Are you sure?')) event.preventDefault(); 
});