リンクを防止し、確認してから、場所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();
}
}
私は間違った方法を確認することを考えていました。確認により、サイトが自動的に開くのを防ぎ、ユーザーの入力を待ちます。したがって、基本的には、PreventDefaultをElseに移動する必要があります。
したがって、[キャンセル]をクリックした場合にのみ、リンクが開くのを防ぎます。これにより、リンクが通常どおりに機能することができます。たとえば、ターゲット= "_ blank"命令がある場合もあります。
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?")});
ダウンロード/リンク確認のためにWebサイトで使用します。
function 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;
}
あなたがアラート/確認を使用したい場合、これは最良の方法です(私は使用することを好みます ブートストラップ確認 また ブートボックス):
$('.confirm-delete').click( function( event ) {
if ( !confirm('Are you sure?') ) event.preventDefault();
});
所属していません StackOverflow