如何暂停<;a>;标签


How to pause execution on <a> tag?

我有代码

<a href="<?php echo site_url('company/remove_company/'.$value['id']).'/'.$value['company_name']; ?>" title="Remove Data"><i class="icon-trash"></i></a>

我有另一个用jquery编写的代码,使用sweetalert函数,如果用户试图删除数据库中的记录,它将弹出一条警告消息。

$(".icon-trash").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() {
        swal("Deleted!", "Your imaginary file has been deleted.", "success");
      });
  });

我的代码的问题是,当用户点击链接时,它会很快弹出,并转到href属性中给出的链接。我想阻止它转到链接,允许弹出窗口保持显示,直到用户决定是单击yes delete it还是cancel,如果用户单击cancel,则不会转到链接。

有什么帮助吗?我不知道该怎么办。

您需要阻止默认操作,成功后,继续进行位置更改:

$(".icon-trash").click(function(e) {
    var that = this;
    // Prevent the default action.                                      « Look here.
    e.preventDefault();
    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() {
        swal("Deleted!", "Your imaginary file has been deleted.", "success");
        // In this confirm, add the location.                           « Look here.
        location.href = $(that).attr("href");
      });
  });

此外,最好不要有任何类型的数据库写入功能,如:

  • 正在创建新条目
  • 正在删除条目

GET方法中。这很危险。因此,您应该考虑通过提供POST方法来更改它,并通过JavaScript/AAJAX执行它。

您也可以通过以下方式实现:

链接:

<a href="<?php echo site_url('company/remove_company/'. $value->id); ?>" class="delete-company">

脚本:

    $('.delete-company').on('click', function(e) {
    var that = $(this);
    swal({   
      title: "Are you sure?",   
      text: "You will not be able to recover this user account!",   
      type: "warning",   
      showCancelButton: true,   
      confirmButtonColor: "#DD6B55",   
      confirmButtonText: "Yes, delete it!",   
      cancelButtonText: "No, cancel please!",   
      closeOnConfirm: false,   
      closeOnCancel: false 
    }, 
    function(isConfirm){   
      if (isConfirm) { 
       location.replace(that.attr('href'));
       swal("Success","User successfully removed!", "success");
    } else {     
      swal("Cancelled", "Removing user accout was cancelled!", "error");   
    }
   });
    e.preventDefault();
  });