删除前如何显示确认消息?


204

我想获得有关单击删除的确认消息(可能是按钮或图像)。如果用户选择“ Ok”,则删除完成,否则,如果“Cancel单击 ”,则不会发生任何事情。

当单击按钮时,我尝试回显此内容,但是回显内容会使我的输入框和文本框失去样式和设计。

Answers:


330

onclick在按钮事件中编写以下代码:

var result = confirm("Want to delete?");
if (result) {
    //Logic to delete the item
}

出色的答案!简短,准确且有效地工作
John

对于任何不熟悉JavaScript的人来说,您的代码行都没有任何意义,该示例看起来并没有定论和令人困惑。尽管如此,这是一个很好的答案。
塞缪尔·拉姆赞

我认为您应该在答案中添加一些细节。为什么将代码插入按钮内而不是将其写在头部或外部文件中?这是一个非常通用的函数,程序员可能想将其多次用于多个按钮,我不会在单个特定按钮内编写它……
franz1

285

您可以如下更好地使用

 <a href="url_to_delete" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a>

2
这应该在线程中进行。简单,快速,有效。做得好吗?
DonExo

非常危险!如果Javascript已关闭怎么办?还是蜘蛛/搜索机器人会阅读此页面?然后它将跟踪所有链接并删除所有内容!一些浏览器插件还遵循页面上的所有链接来对其进行预缓存。永远不要这样!删除绝不应是GET请求。
Daniele Testa

它的安全性不亚于排名第一的答案,如果关闭JavaScript,任何JavaScript都是危险的。开启或关闭JavaScript是用户的个人选择,如果关闭JavaScript,则用户应该更好地了解不要在任何网站上按下任何按钮。总有服务器端验证是一个很好的选择。
塞缪尔·拉姆赞

53

这是使用不干扰JavaScript并在HTML中保留确认消息的方式。

<a href="/delete" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>

这是纯香草JS,与IE 9+兼容:

var deleteLinks = document.querySelectorAll('.delete');

for (var i = 0; i < deleteLinks.length; i++) {
  deleteLinks[i].addEventListener('click', function(event) {
      event.preventDefault();

      var choice = confirm(this.getAttribute('data-confirm'));

      if (choice) {
        window.location.href = this.getAttribute('href');
      }
  });
}

实际观看:http : //codepen.io/anon/pen/NqdKZq


这完美地工作,但仅适用于第一个按钮。如果我们有20个或更多,该怎么办?谢谢!
情绪化

1
没错,这是因为querySelector仅匹配第一个元素。我已经编辑了答案,并分叉了Codepen以使用querySelectorAll代替。
DevAntoine

如果将此示例进行编辑以使其在禁用JavaScript的情况下也可以使用,href="https://stackoverflow.com/delete"那么我认为就足够了。或表单提交示例。
西罗桑蒂利郝海东冠状病六四事件法轮功

1
@CiroSantilli巴拿马文件六四事件法轮功有了event.preventDefault()函数,情况已经如此。您可以使用网址替换哈希字符,它不会被触发。但是,如果禁用JavaScript,则该链接将按预期工作。
DevAntoine '16

1
@CiroSantilli巴拿马文件六四事件法轮功;)
DevAntoine

28
function ConfirmDelete()
{
  var x = confirm("Are you sure you want to delete?");
  if (x)
      return true;
  else
    return false;
}


<input type="button" onclick="ConfirmDelete()">

我认为最好只有1个返回点。所以我更喜欢
jedi

17
或者只是return confirm("…")。无需分配一个布尔值的变量,然后转移到if / else中。
slhck 2014年


13

这很简单,只需一行代码

<a href="#" title="delete" class="delete" onclick="return confirm('Are you sure you want to delete this item')">Delete</a>

似乎在可接受的答案下方已经有这样的答案。
帽子

12

在user1697128上有所改进(因为我无法对此发表评论)

<script>
    function ConfirmDelete()
    {
      var x = confirm("Are you sure you want to delete?");
      if (x)
          return true;
      else
        return false;
    }
</script>    

<button Onclick="return ConfirmDelete();" type="submit" name="actiondelete" value="1"><img src="images/action_delete.png" alt="Delete"></button>

如果按取消,将取消表单提交


8

我想提供我的方法:

<form action="/route" method="POST">
<input type="hidden" name="_method" value="DELETE"> 
<input type="hidden" name="_token" value="the_token">
<button type="submit" class="btn btn-link" onclick="if (!confirm('Are you sure?')) { return false }"><span>Delete</span></button>
</form>

6

的HTML

<input onclick="return myConfirm();" type="submit" name="deleteYear" class="btn btn-danger" value="Delete">

Java脚本

<script>
function myConfirm() {
  var result = confirm("Want to delete?");
  if (result==true) {
   return true;
  } else {
   return false;
  }
}


4

HTML:

<a href="#" class="delete" data-confirm="Are you sure to delete this item?">Delete</a>

使用jQuery:

$('.delete').on("click", function (e) {
    e.preventDefault();

    var choice = confirm($(this).attr('data-confirm'));

    if (choice) {
        window.location.href = $(this).attr('href');
    }
});

DevAntoines答案的很好的jQuery适应(stackoverflow.com/a/19973570/1337887)。但是,稍微通用一点的方法是使用“ $('A [数据确认]')”而不是“ $('。delete')”。这样,您不需要按钮具有删除类,而只需集成data-confirm属性。
弗洛里安


4
<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>

<!-- language: lang-js -->
<script>
function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
                setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            } else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }
        }
    });
}
</script>


3

如果您对完成CSS格式的快速解决方案感兴趣,可以使用SweetAlert

$(function(){
  $(".delete").click(function(){
      swal({   
	  	  title: "Are you sure?",   
		  text: "You will not be able to recover this imaginary file!",   
		  type: "warning",   
		  showCancelButton: true,   
	  	  confirmButtonColor: "#DD6B55",   
	  	  confirmButtonText: "Yes, delete it!",   
	  	  closeOnConfirm: false 
	  }, 
	  function(isConfirmed){ 
        if(isConfirmed) {
          $(".file").addClass("isDeleted");
          swal("Deleted!", "Your imaginary file has been deleted.", "success"); 
        }
      }
    );
  });
});
html { zoom: 0.7 } /* little "hack" to make example visible in stackoverflow snippet preview */
body > p { font-size: 32px }

.delete { cursor: pointer; color: #00A }
.isDeleted { text-decoration:line-through }
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://t4t5.github.io/sweetalert/dist/sweetalert-dev.js"></script>
<link rel="stylesheet" href="http://t4t5.github.io/sweetalert/dist/sweetalert.css">

<p class="file">File 1 <span class="delete">(delete)</span></p>


2

当您在php&mysql中删除某些内容时设置一个确认消息...

使用以下脚本代码:

<script>
    function Conform_Delete()
    {
       return conform("Are You Sure Want to Delete?");
    }
</script>

使用此html代码:

<a onclick="return Conform_Delete()" href="#">delete</a>

2
var txt;
var r = confirm("Press a button!");
if (r == true) {
   txt = "You pressed OK!";
} else {
   txt = "You pressed Cancel!";
}

var txt;
var r = confirm("Press a button!");
if (r == true) {
    txt = "You pressed OK!";
} else {
    txt = "You pressed Cancel!";
}


1

使用jQuery:

$(".delete-link").on("click", null, function(){
        return confirm("Are you sure?");
    });

1

我知道这很旧,但是我需要一个答案,但没有一个答案,但是alpesh的答案对我有用,并且想与可能遇到相同问题的人分享。

<script>    
function confirmDelete(url) {
    if (confirm("Are you sure you want to delete this?")) {
        window.open(url);
    } else {
        false;
    }       
}
</script>

普通版:

<input type="button" name="delete" value="Delete" onClick="confirmDelete('delete.php?id=123&title=Hello')">

我的PHP版本:

$deleteUrl = "delete.php?id=" .$id. "&title=" .$title;
echo "<input type=\"button\" name=\"delete\" value=\"Delete\" onClick=\"confirmDelete('" .$deleteUrl. "')\"/>";

这可能不是公开进行的正确方法,但这对我来说是在私有站点上起作用的。:)


1

非常简单

function archiveRemove(any) {
    var click = $(any);
    var id = click.attr("id");
    swal.fire({
        title: 'Are you sure !',
           text: "?????",
           type: 'warning',
           showCancelButton: true,
           confirmButtonColor: '#3085d6',
           cancelButtonColor: '#d33',
           confirmButtonText: 'yes!',
           cancelButtonText: 'no'
    }).then(function (success) {
        if (success) {
            $('a[id="' + id + '"]').parents(".archiveItem").submit();
        }
    })
}

0
function del_confirm(msg,url)
        {
            if(confirm(msg))
            {
                window.location.href=url
            }
            else
            {
                false;
            }

        }



<a  onclick="del_confirm('Are you Sure want to delete this record?','<filename>.php?action=delete&id=<?<id> >')"href="#"></a>

0
<SCRIPT LANGUAGE="javascript">
function Del()
{
var r=confirm("Are you sure?")
if(r==true){return href;}else{return false;}
}
</SCRIPT>

您的链接:

<a href='edit_post.php?id=$myrow[id]'> Delete</a>

0

函数调用后,onclick处理程序应返回false。例如。

onclick="ConfirmDelete(); return false;">


0

我认为最简单的解决方案是:

链接:

<a href="http://link_to_go_to_on_success" class="delete">Delete</a>

Javascript:

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

0
<a href="javascript:;" onClick="if(confirm('Are you sure you want to delete this product')){del_product(id);}else{ }" class="btn btn-xs btn-danger btn-delete" title="Del Product">Delete Product</a>


function del_product(id){
    $('.process').css('display','block');
    $('.process').html('<img src="./images/loading.gif">');
    $.ajax({
        'url':'./process.php?action=del_product&id='+id,
        'type':"post",
        success: function(result){
            info=JSON.parse(result);
            if(result.status==1){
            setTimeout(function(){
                    $('.process').hide();
                    $('.tr_'+id).hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);
            }else if(result.status==0){
                setTimeout(function(){
                    $('.process').hide();
                },3000);
                setTimeout(function(){
                    $('.process').html(result.notice);
                },1000);

                }
            }
        });
}

0

这是纯JS中使用className及其绑定事件的另一个简单示例。

var eraseable =  document.getElementsByClassName("eraseable");

for (var i = 0; i < eraseable.length; i++) {
    eraseable[i].addEventListener('click', delFunction, false); //bind delFunction on click to eraseables
}

function delFunction(){        
     var msg = confirm("Are you sure?");      
     if (msg == true) { 
        this.remove(); //remove the clicked element if confirmed
    }   
  };
<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>

<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>

<button class="eraseable">
<img class="eraseable" src="http://zelcs.com/wp-content/uploads/2013/02/stackoverflow-logo-dumpster.jpg" style="width:100px;height:auto;">
Delete me</button>


0
<script>
function deleteItem()
{
   var resp = confirm("Do you want to delete this item???");
   if (resp == true) {
      //do something
   } 
   else {
      //do something
   }
}
</script>

使用以下函数调用此函数 onClick


0

对于“删除时确认消息”,请使用:

                       $.ajax({
                        type: "POST",
                        contentType: "application/json; charset=utf-8",
                        url: "Searching.aspx/Delete_Student_Data",
                        data: "{'StudentID': '" + studentID + "'}",
                        dataType: "json",
                        success: function (data) {
                            alert("Delete StudentID Successfully");
                            return true;
                        }

0

带有Javascript的Angularjs删除示例

HTML代码

<button ng-click="ConfirmDelete(single_play.play_id)" type="submit" name="actiondelete" value="1"><img src="images/remove.png" alt="Delete"></button>

“ single_play.play_id”是任何angularjs变量,假设您要在删除操作期间传递任何参数

app模块内的Angularjs代码

$scope.ConfirmDelete = function(yy)
        {
            var x = confirm("Are you sure you want to delete?");
            if (x) {
             // Action for press ok
                $http({
                method : 'POST',
                url : 'sample.php',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                data: $.param({ delete_play_id : yy})
                }).then(function (response) { 
                $scope.message = response.data;
                });
            }
            else {
             //Action for cancel
                return false;
            }
        } 

0

对于选择选项框,要执行此操作要困难得多。解决方法如下:

<select onchange="if (this.value == 'delete' && !confirm('THIS ACTION WILL DELETE IT!\n\nAre you sure?')){this.value=''}">
    <option value=''> &nbsp; </option>
    <option value="delete">Delete Everything</option>
</select>

0

我在laravel中使用这种方式-

<form id="delete-{{$category->id}}" action="{{route('category.destroy',$category->id)}}" style="display: none;" method="POST">
 @csrf
 @method('DELETE')
</form>

<a href="#" onclick="if (confirm('Are you sure want to delete this item?')) {
           event.preventDefault();
           document.getElementById('delete-{{$category->id}}').submit();
         }else{
           event.preventDefault();
         }">
  <i class="fa fa-trash"></i>
</a>
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.