【问题标题】:Confirm deletion in modal / dialog using Twitter Bootstrap?使用 Twitter Bootstrap 在模态/对话框中确认删除?
【发布时间】:2012-02-17 10:21:52
【问题描述】:

我有一个与数据库行绑定的 HTML 行表。我想为每一行设置一个“删除行”链接,但我想事先与用户确认。

有没有办法使用 Twitter Bootstrap 模式对话框来做到这一点?

【问题讨论】:

  • 遇到这个问题后,我想加入(在我看来)这样一个简单且更精简的“修复”问题。我挣扎了一会儿,然后意识到它可以多么简单:只需将实际的表单提交按钮放在模态对话框中,然后表单本身的提交按钮什么都不做,只是触发对话框窗口......问题解决了。
  • @jonijones 这个例子对我不起作用(点击第一个按钮时不显示确认消息)-在 chrome 中测试

标签: jquery twitter-bootstrap


【解决方案1】:

获取食谱

对于这个任务,您可以使用已经可用的插件和引导扩展。或者您可以只用 3 行代码制作自己的确认弹出窗口。看看吧。

假设我们有这个链接(注意 data-href 而不是 href)或我们想要删除确认的按钮:

<a href="#" data-href="delete.php?id=23" data-toggle="modal" data-target="#confirm-delete">Delete record #23</a>

<button class="btn btn-default" data-href="/delete.php?id=54" data-toggle="modal" data-target="#confirm-delete">
    Delete record #54
</button>

这里 #confirm-delete 指向 HTML 中的模态弹出 div。它应该有一个这样配置的“确定”按钮:

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                ...
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>

现在您只需要这个小 javascript 即可确认删除操作:

$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});

所以在show.bs.modal事件删除按钮href被设置为具有相应记录ID的URL。

演示: http://plnkr.co/edit/NePR0BQf3VmKtuMmhVR7?p=preview


POST 配方

我意识到在某些情况下可能需要执行 POST 或 DELETE 请求而不是 GET。没有太多代码,它仍然很简单。用这种方法看看下面的演示:

// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {

  var $modalDiv = $(e.delegateTarget);
  var id = $(this).data('recordId');

  $modalDiv.addClass('loading');
  $.post('/api/record/' + id).then(function() {
     $modalDiv.modal('hide').removeClass('loading');
  });
});

// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
  var data = $(e.relatedTarget).data();
  $('.title', this).text(data.recordTitle);
  $('.btn-ok', this).data('recordId', data.recordId);
});

// Bind click to OK button within popup
$('#confirm-delete').on('click', '.btn-ok', function(e) {

  var $modalDiv = $(e.delegateTarget);
  var id = $(this).data('recordId');

  $modalDiv.addClass('loading');
  setTimeout(function() {
    $modalDiv.modal('hide').removeClass('loading');
  }, 1000);

  // In reality would be something like this
  // $modalDiv.addClass('loading');
  // $.post('/api/record/' + id).then(function() {
  //   $modalDiv.modal('hide').removeClass('loading');
  // });
});

// Bind to modal opening to set necessary data properties to be used to make request
$('#confirm-delete').on('show.bs.modal', function(e) {
  var data = $(e.relatedTarget).data();
  $('.title', this).text(data.recordTitle);
  $('.btn-ok', this).data('recordId', data.recordId);
});
.modal.loading .modal-content:before {
  content: 'Loading...';
  text-align: center;
  line-height: 155px;
  font-size: 20px;
  background: rgba(0, 0, 0, .8);
  position: absolute;
  top: 55px;
  bottom: 0;
  left: 0;
  right: 0;
  color: #EEE;
  z-index: 1000;
}
<script data-require="jquery@*" data-semver="2.0.3" src="//code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="bootstrap@*" data-semver="3.1.1" src="//netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
<link data-require="bootstrap-css@3.1.1" data-semver="3.1.1" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css" />

<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h4 class="modal-title" id="myModalLabel">Confirm Delete</h4>
      </div>
      <div class="modal-body">
        <p>You are about to delete <b><i class="title"></i></b> record, this procedure is irreversible.</p>
        <p>Do you want to proceed?</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-danger btn-ok">Delete</button>
      </div>
    </div>
  </div>
</div>
<a href="#" data-record-id="23" data-record-title="The first one" data-toggle="modal" data-target="#confirm-delete">
        Delete "The first one", #23
    </a>
<br />
<button class="btn btn-default" data-record-id="54" data-record-title="Something cool" data-toggle="modal" data-target="#confirm-delete">
  Delete "Something cool", #54
</button>

演示: http://plnkr.co/edit/V4GUuSueuuxiGr4L9LmG?p=preview


引导程序 2.3

这是我为 Bootstrap 2.3 modal 回答这个问题时编写的代码的原始版本。

$('#modal').on('show', function() {
    var id = $(this).data('id'),
        removeBtn = $(this).find('.danger');
    removeBtn.attr('href', removeBtn.attr('href').replace(/(&|\?)ref=\d*/, '$1ref=' + id));
});

演示:http://jsfiddle.net/MjmVr/1595/

【讨论】:

  • 这几乎可以完美运行,但即使在小提琴版本中(如在我的网站中),ID 也不会传递给模式中的“是”按钮。我确实注意到您正在尝试替换 &ref 而不是 ?ref 所以我尝试更改它,但它仍然无法正常工作。我在这里错过了其他东西吗?这很好,所以 TIA 为您提供帮助!
  • 谢谢@dfsq - 这很好用。单击“否”按钮时对话框不会隐藏,因此我将 href 更改为 # 而不是模态隐藏,并且效果也很好。再次感谢您的帮助。
  • 一个调整是最终的删除请求应该产生一个帖子,而不是像链接那样的 GEt。如果您允许在 GET 上删除,则恶意第三方可以轻松地在网站或电子邮件上制作链接,从而导致您的用户无意中删除内容。这可能看起来很愚蠢,但在某些情况下这将是一个严重的安全问题。
  • 您可能想看看Vex。做你要求的事情要简单得多:jsfiddle.net/adamschwartz/hQump.
  • 很想反对使用 GET 执行破坏性操作。你不应该这样做的原因有很多很多。
【解决方案2】:

http://bootboxjs.com/ - Bootstrap 3.0.0 的最新作品

最简单的例子:

bootbox.alert("Hello world!"); 

来自网站:

该库公开了三种旨在模仿其原生 JavaScript 等效项的方法。它们的确切方法签名很灵活,因为每个都可以采用各种参数来自定义标签并指定默认值,但它们最常见的调用方式如下:

bootbox.alert(message, callback)
bootbox.prompt(message, callback)
bootbox.confirm(message, callback)

这是一个运行中的 sn-p(单击下面的“运行代码 sn-p”):

$(function() {
  bootbox.alert("Hello world!");
});
<!-- required includes -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>

<!-- bootbox.js at 4.4.0 -->
<script src="https://rawgit.com/makeusabrew/bootbox/f3a04a57877cab071738de558581fbc91812dce9/bootbox.js"></script>

【讨论】:

  • 不幸的是,当您需要在标题和按钮上使用非英文文本时,您要么必须修改 JS,要么开始参数化,几乎与自己添加引导 html 和 JS 一样多。 :)
【解决方案3】:
  // ---------------------------------------------------------- Generic Confirm  

  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal hide fade">' +    
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    });

    confirmModal.modal('show');     
  };

  // ---------------------------------------------------------- Confirm Put To Use

  $("i#deleteTransaction").live("click", function(event) {
    // get txn id from current table row
    var id = $(this).data('id');

    var heading = 'Confirm Transaction Delete';
    var question = 'Please confirm that you wish to delete transaction ' + id + '.';
    var cancelButtonTxt = 'Cancel';
    var okButtonTxt = 'Confirm';

    var callback = function() {
      alert('delete confirmed ' + id);
    };

    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

  });

【讨论】:

  • 这是一篇旧帖子,但我想做同样的事情,但是当我使用上面的代码时,模态对话框会显示?
【解决方案4】:

我意识到这是一个非常古老的问题,但是因为我今天想知道一种更有效的方法来处理引导模式。我做了一些研究,发现比上面显示的解决方案更好,可以在此链接中找到:

http://www.petefreitag.com/item/809.cfm

首先加载jquery

$(document).ready(function() {
    $('a[data-confirm]').click(function(ev) {
        var href = $(this).attr('href');

        if (!$('#dataConfirmModal').length) {
            $('body').append('<div id="dataConfirmModal" class="modal" role="dialog" aria-labelledby="dataConfirmLabel" aria-hidden="true"><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="dataConfirmLabel">Please Confirm</h3></div><div class="modal-body"></div><div class="modal-footer"><button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button><a class="btn btn-primary" id="dataConfirmOK">OK</a></div></div>');
        } 
        $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm'));
        $('#dataConfirmOK').attr('href', href);
        $('#dataConfirmModal').modal({show:true});
        return false;
    });
});

然后只需向 href 提出任何问题/确认:

<a href="/any/url/delete.php?ref=ID" data-confirm="Are you sure you want to delete?">Delete</a>

这种方式确认模式更加通用,因此可以轻松地在您网站的其他部分重复使用。

【讨论】:

  • 请勿在未注明出处的情况下发布来自其他来源的代码:petefreitag.com/item/809.cfm.
  • 尽管操作员一开始忘记了归属,但这对我来说是完美的。像魅力一样工作。
  • 我认为使用 GET http 请求删除项目不是一个好主意
  • 妈妈告诉我不要点击任何冷聚变链接
  • @BenY 这不是关于用户是否有权做某事,而是关于已经有权做某事的恶意用户被诱骗点击其他网站上的链接,电子邮件等,以便恶意用户可以利用该用户的权限。
【解决方案5】:

感谢@Jousby 的solution,我设法让我的工作正常,但发现我必须稍微改进他的解决方案的 Bootstrap 模态标记以使其正确呈现,如官方 examples 所示。

所以,这是我对通用 confirm 函数的修改版本,它运行良好:

/* Generic Confirm func */
  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal fade">' +        
          '<div class="modal-dialog">' +
          '<div class="modal-content">' +
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#!" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#!" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
          '</div>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    }); 

    confirmModal.modal('show');    
  };  
/* END Generic Confirm func */

【讨论】:

  • 这里的解决方案很好。我做了一些细微的修改来处理取消链接的回调。一个小建议使用#!而不是 # 在你的 href 中防止页面滚动到顶部。
  • 如果我可以加倍投票,我会的。漂亮而优雅。谢谢。
  • 非常好的解决方案。我可以建议的另一个改进是添加另一个参数:btnType = "btn-primary",然后将 OK 按钮的代码更改为包含 class="btn ' + btnType + '"。这样就可以传递一个可选参数来更改 OK 按钮的外观,例如 btn-danger 用于删除。
【解决方案6】:

我发现它有用且易于使用,而且看起来很漂亮:http://maxailloud.github.io/confirm-bootstrap/。

要使用它,请在页面中包含 .js 文件,然后运行:

$('your-link-selector').confirmModal();

您可以对其应用多种选项,以使其在确认删除时看起来更好,我使用:

$('your-link-selector').confirmModal({
    confirmTitle: 'Please confirm',
    confirmMessage: 'Are you sure you want to delete this?',
    confirmStyle: 'danger',
    confirmOk: '<i class="icon-trash icon-white"></i> Delete',
    confirmCallback: function (target) {
         //perform the deletion here, or leave this option
         //out to just follow link..
    }
});

【讨论】:

  • 这是一个不错的库
【解决方案7】:

我可以使用 bootbox.js 库轻松处理此类任务。首先,您需要包含 bootbox JS 文件。然后在您的事件处理函数中简单地编写以下代码:

    bootbox.confirm("Are you sure to want to delete , function(result) {

    //here result will be true
    // delete process code goes here

    });

官方 bootboxjs site

【讨论】:

    【解决方案8】:

    以下解决方案优于 bootbox.js,因为

    • bootbox.js 能做的一切都能做;
    • 使用语法更简单
    • 它允许您使用“错误”、“警告”或“信息”优雅地控制消息的颜色
    • Bootbox 有 986 行,我的只有 110 行

    digimango.messagebox.js:

    const dialogTemplate = '\
        <div class ="modal" id="digimango_messageBox" role="dialog">\
            <div class ="modal-dialog">\
                <div class ="modal-content">\
                    <div class ="modal-body">\
                        <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\
                        <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\
                    </div>\
                    <div class ="modal-footer">\
                        <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\
                        <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\
                    </div>\
                </div>\
            </div>\
        </div>';
    
    
    // See the comment inside function digimango_onOkClick(event) {
    var digimango_numOfDialogsOpened = 0;
    
    
    function messageBox(msg, significance, options, actionConfirmedCallback) {
        if ($('#digimango_MessageBoxContainer').length == 0) {
            var iDiv = document.createElement('div');
            iDiv.id = 'digimango_MessageBoxContainer';
            document.getElementsByTagName('body')[0].appendChild(iDiv);
            $("#digimango_MessageBoxContainer").html(dialogTemplate);
        }
    
        var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;
    
        if (options == null) {
            okButtonName = 'OK';
            cancelButtonName = null;
            showTextBox = null;
            textBoxDefaultText = null;
        } else {
            okButtonName = options.okButtonName;
            cancelButtonName = options.cancelButtonName;
            showTextBox = options.showTextBox;
            textBoxDefaultText = options.textBoxDefaultText;
        }
    
        if (showTextBox == true) {
            if (textBoxDefaultText == null)
                $('#digimango_messageBoxTextArea').val('');
            else
                $('#digimango_messageBoxTextArea').val(textBoxDefaultText);
    
            $('#digimango_messageBoxTextArea').show();
        }
        else
            $('#digimango_messageBoxTextArea').hide();
    
        if (okButtonName != null)
            $('#digimango_messageBoxOkButton').html(okButtonName);
        else
            $('#digimango_messageBoxOkButton').html('OK');
    
        if (cancelButtonName == null)
            $('#digimango_messageBoxCancelButton').hide();
        else {
            $('#digimango_messageBoxCancelButton').show();
            $('#digimango_messageBoxCancelButton').html(cancelButtonName);
        }
    
        $('#digimango_messageBoxOkButton').unbind('click');
        $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);
    
        $('#digimango_messageBoxCancelButton').unbind('click');
        $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);
    
        var content = $("#digimango_messageBoxMessage");
    
        if (significance == 'error')
            content.attr('class', 'text-danger');
        else if (significance == 'warning')
            content.attr('class', 'text-warning');
        else
            content.attr('class', 'text-success');
    
        content.html(msg);
    
        if (digimango_numOfDialogsOpened == 0)
            $("#digimango_messageBox").modal();
    
        digimango_numOfDialogsOpened++;
    }
    
    function digimango_onOkClick(event) {
        // JavaScript's nature is unblocking. So the function call in the following line will not block,
        // thus the last line of this function, which is to hide the dialog, is executed before user
        // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count
        // how many dialogs is currently showing. If we know there is still a dialog being shown, we do
        // not execute the last line in this function.
        if (typeof (event.data.callback) != 'undefined')
            event.data.callback($('#digimango_messageBoxTextArea').val());
    
        digimango_numOfDialogsOpened--;
    
        if (digimango_numOfDialogsOpened == 0)
            $('#digimango_messageBox').modal('hide');
    }
    
    function digimango_onCancelClick() {
        digimango_numOfDialogsOpened--;
    
        if (digimango_numOfDialogsOpened == 0)
            $('#digimango_messageBox').modal('hide');
    }

    使用 digimango.messagebox.js:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>A useful generic message box</title>
        <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    
        <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />
        <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
        <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>
        <script src="~/Scripts/bootbox.js" type="text/javascript"></script>
    
        <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>
    
    
        <script type="text/javascript">
            function testAlert() {
                messageBox('Something went wrong!', 'error');
            }
    
            function testAlertWithCallback() {
                messageBox('Something went wrong!', 'error', null, function () {
                    messageBox('OK clicked.');
                });
            }
    
            function testConfirm() {
                messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {
                    messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });
                });
            }
    
            function testPrompt() {
                messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {
                    messageBox('User entered "' + userInput + '".');
                });
            }
    
            function testPromptWithDefault() {
                messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {
                    messageBox('User entered "' + userInput + '".');
                });
            }
    
        </script>
    </head>
    
    <body>
        <a href="#" onclick="testAlert();">Test alert</a> <br/>
        <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />
        <a href="#" onclick="testConfirm();">Test confirm</a> <br/>
        <a href="#" onclick="testPrompt();">Test prompt</a><br />
        <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />
    </body>
    
    </html>

    【讨论】:

      【解决方案9】:

      当涉及到一个相关的大项目时,我们可能需要一些可重复使用的东西。这是我在 SO 的帮助下带来的。

      确认删除.jsp

      <!-- Modal Dialog -->
      <div class="modal fade" id="confirmDelete" role="dialog" aria-labelledby="confirmDeleteLabel"
       aria-hidden="true">
      <div class="modal-dialog">
          <div class="modal-content">
              <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal"
                          aria-hidden="true">&times;</button>
                  <h4 class="modal-title">Delete Parmanently</h4>
              </div>
              <div class="modal-body" style="height: 75px">
                  <p>Are you sure about this ?</p>
              </div>
              <div class="modal-footer">
                  <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                  <button type="button" class="btn btn-danger" id="confirm-delete-ok">Ok
                  </button>
              </div>
          </div>
      </div>
      

      <script type="text/javascript">
      
          var url_for_deletion = "#";
          var success_redirect = window.location.href;
      
      $('#confirmDelete').on('show.bs.modal', function (e) {
          var message = $(e.relatedTarget).attr('data-message');
          $(this).find('.modal-body p').text(message);
          var title = $(e.relatedTarget).attr('data-title');
          $(this).find('.modal-title').text(title);
      
          if (typeof  $(e.relatedTarget).attr('data-url') != 'undefined') {
              url_for_deletion = $(e.relatedTarget).attr('data-url');
          }
          if (typeof  $(e.relatedTarget).attr('data-success-url') != 'undefined') {
              success_redirect = $(e.relatedTarget).attr('data-success-url');
          }
      
      });
      
      <!-- Form confirm (yes/ok) handler, submits form -->
      $('#confirmDelete').find('.modal-footer #confirm-delete-ok').on('click', function () {
          $.ajax({
              method: "delete",
              url: url_for_deletion,
          }).success(function (data) {
              window.location.href = success_redirect;
          }).fail(function (error) {
              console.log(error);
          });
          $('#confirmDelete').modal('hide');
          return false;
      });
      <script/>
      

      重用Page.jsp

      <a href="#" class="table-link danger"
      data-toggle="modal"
      data-target="#confirmDelete"
      data-title="Delete Something"
      data-message="Are you sure you want to inactivate this something?"
      data-url="client/32"
      id="delete-client-32">
      </a>
      <!-- jQuery should come before this -->
      <%@ include file="../some/path/confirmDelete.jsp" %>
      

      注意: 删除请求使用 http delete 方法,您可以从 javascript 更改它,也可以使用 data-title 或 data-url 等中的 data-attribute 发送它,以获得支持任何请求。

      【讨论】:

        【解决方案10】:

        如果你想用最简单的快捷方式来做,那么你可以用this plugin来做。


        但是这个插件是使用Bootstrap Modal 的替代实现。而且真正的Bootstrap实现也很简单,所以我不喜欢用这个插件,因为它在页面中添加了过多的JS内容,会拖慢页面加载时间。


        想法

        我喜欢这样自己实现-

        1. 如果用户单击按钮从列表中删除项目,那么 JS 调用会将 项目 ID(或任何更重要的数据)放入表单中在模态中。
        2. 然后在弹窗中会有2个确认按钮。

          • 是的将提交表单(使用 ajax 或直接提交表单)
          • 否只会关闭模式

        代码会是这样的(使用Bootstrap)-

        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
          <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        
        <script>
        $(document).ready(function()
        {
            $("button").click(function()
            {
                //Say - $('p').get(0).id - this delete item id
                $("#delete_item_id").val( $('p').get(0).id );
                $('#delete_confirmation_modal').modal('show');
            });
        });
        </script>
        
        <p id="1">This is a item to delete.</p>
        
        <button type="button" class="btn btn-danger">Delete</button>
        
        <!-- Delete Modal content-->
        
        <div class="modal fade" id="delete_confirmation_modal" role="dialog" style="display: none;">
        	<div class="modal-dialog" style="margin-top: 260.5px;">
        				<div class="modal-content">
        			<div class="modal-header">
        				<button type="button" class="close" data-dismiss="modal">×</button>
        				<h4 class="modal-title">Do you really want to delete this Category?</h4>
        			</div>
        			<form role="form" method="post" action="category_delete" id="delete_data">
        				<input type="hidden" id="delete_item_id" name="id" value="12">
        				<div class="modal-footer">
        					<button type="submit" class="btn btn-danger">Yes</button>
        					<button type="button" class="btn btn-primary" data-dismiss="modal">No</button>
        				</div>
        			</form>
        		</div>
        
        	</div>
        </div>

        您应该根据您的要求更改表单操作。

        愉快的编码:)

        【讨论】:

          【解决方案11】:

          您可以使用 callback 功能尝试更多可重用我的解决方案。在此功能中,您可以使用 POST 请求或一些逻辑。 使用的库:JQuery 3> 和 Bootstrap 3>。

          https://jsfiddle.net/axnikitenko/gazbyv8v/

          用于测试的 HTML 代码:

          ...
          <body>
              <a href='#' id="remove-btn-a-id" class="btn btn-default">Test Remove Action</a>
          </body>
          ...
          

          Javascript:

          $(function () {
              function remove() {
                  alert('Remove Action Start!');
              }
              // Example of initializing component data
              this.cmpModalRemove = new ModalConfirmationComponent('remove-data', remove,
                  'remove-btn-a-id', {
                      txtModalHeader: 'Header Text For Remove', txtModalBody: 'Body For Text Remove',
                      txtBtnConfirm: 'Confirm', txtBtnCancel: 'Cancel'
                  });
              this.cmpModalRemove.initialize();
          });
          
          //----------------------------------------------------------------------------------------------------------------------
          // COMPONENT SCRIPT
          //----------------------------------------------------------------------------------------------------------------------
          /**
           * Script processing data for confirmation dialog.
           * Used libraries: JQuery 3> and Bootstrap 3>.
           *
           * @param name unique component name at page scope
           * @param callback function which processing confirm click
           * @param actionBtnId button for open modal dialog
           * @param text localization data, structure:
           *              > txtModalHeader - text at header of modal dialog
           *              > txtModalBody - text at body of modal dialog
           *              > txtBtnConfirm - text at button for confirm action
           *              > txtBtnCancel - text at button for cancel action
           *
           * @constructor
           * @author Aleksey Nikitenko
           */
          function ModalConfirmationComponent(name, callback, actionBtnId, text) {
              this.name = name;
              this.callback = callback;
              // Text data
              this.txtModalHeader =   text.txtModalHeader;
              this.txtModalBody =     text.txtModalBody;
              this.txtBtnConfirm =    text.txtBtnConfirm;
              this.txtBtnCancel =     text.txtBtnCancel;
              // Elements
              this.elmActionBtn = $('#' + actionBtnId);
              this.elmModalDiv = undefined;
              this.elmConfirmBtn = undefined;
          }
          
          /**
           * Initialize needed data for current component object.
           * Generate html code and assign actions for needed UI
           * elements.
           */
          ModalConfirmationComponent.prototype.initialize = function () {
              // Generate modal html and assign with action button
              $('body').append(this.getHtmlModal());
              this.elmActionBtn.attr('data-toggle', 'modal');
              this.elmActionBtn.attr('data-target', '#'+this.getModalDivId());
              // Initialize needed elements
              this.elmModalDiv =  $('#'+this.getModalDivId());
              this.elmConfirmBtn = $('#'+this.getConfirmBtnId());
              // Assign click function for confirm button
              var object = this;
              this.elmConfirmBtn.click(function() {
                  object.elmModalDiv.modal('toggle'); // hide modal
                  object.callback(); // run callback function
              });
          };
          
          //----------------------------------------------------------------------------------------------------------------------
          // HTML GENERATORS
          //----------------------------------------------------------------------------------------------------------------------
          /**
           * Methods needed for get html code of modal div.
           *
           * @returns {string} html code
           */
          ModalConfirmationComponent.prototype.getHtmlModal = function () {
              var result = '<div class="modal fade" id="' + this.getModalDivId() + '"';
              result +=' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
              result += '<div class="modal-dialog"><div class="modal-content"><div class="modal-header">';
              result += this.txtModalHeader + '</div><div class="modal-body">' + this.txtModalBody + '</div>';
              result += '<div class="modal-footer">';
              result += '<button type="button" class="btn btn-default" data-dismiss="modal">';
              result += this.txtBtnCancel + '</button>';
              result += '<button id="'+this.getConfirmBtnId()+'" type="button" class="btn btn-danger">';
              result += this.txtBtnConfirm + '</button>';
              return result+'</div></div></div></div>';
          };
          
          //----------------------------------------------------------------------------------------------------------------------
          // UTILITY
          //----------------------------------------------------------------------------------------------------------------------
          /**
           * Get id element with name prefix for this component.
           *
           * @returns {string} element id
           */
          ModalConfirmationComponent.prototype.getModalDivId = function () {
              return this.name + '-modal-id';
          };
          
          /**
           * Get id element with name prefix for this component.
           *
           * @returns {string} element id
           */
          ModalConfirmationComponent.prototype.getConfirmBtnId = function () {
              return this.name + '-confirm-btn-id';
          };
          

          【讨论】:

            【解决方案12】:

            带有导航到目标页面和可重复使用的 Blade 文件的 POST 配方

            dfsq 的回答非常好。我对其进行了一些修改以满足我的需要:我实际上需要一个模式,以便在单击后,用户也会被导航到相应的页面。异步执行查询并不总是需要的。

            使用Blade我创建了文件resources/views/includes/confirmation_modal.blade.php:

            <div class="modal fade" id="confirmation-modal" tabindex="-1" role="dialog" aria-labelledby="confirmation-modal-label" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4>{{ $headerText }}</h4>
                        </div>
                        <div class="modal-body">
                            {{ $bodyText }}
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <form action="" method="POST" style="display:inline">
                                {{ method_field($verb) }}
                                {{ csrf_field() }}
                                <input type="submit" class="btn btn-danger btn-ok" value="{{ $confirmButtonText }}" />
                            </form>
                        </div>
                    </div>
                </div>
            </div>
            
            <script>
                $('#confirmation-modal').on('show.bs.modal', function(e) {
                    href = $(e.relatedTarget).data('href');
            
                    // change href of button to corresponding target
                    $(this).find('form').attr('action', href);
                });
            </script>
            

            现在,使用它很简单:

            <a data-href="{{ route('data.destroy', ['id' => $data->id]) }}" data-toggle="modal" data-target="#confirmation-modal" class="btn btn-sm btn-danger">Remove</a>
            

            这里没有太大变化,可以像这样包含模态:

            @include('includes.confirmation_modal', ['headerText' => 'Delete Data?', 'bodyText' => 'Do you really want to delete these data? This operation is irreversible.',
            'confirmButtonText' => 'Remove Data', 'verb' => 'DELETE'])
            

            只要把动词放在那里,它就会使用它。这样,CSRF 也被利用了。

            帮助了我,也许它帮助了别人。

            【讨论】:

              【解决方案13】:

              这是我用于引导的确认框“jquery 组件” 只需在您的代码中使用它:

              function ConfirmBox({title,message,result}){
               let confirm = $(`
                          <div class="modal fade" tabindex="-1" id="confirmBox" role="dialog" aria-labelledby="modalLabelSmall" aria-hidden="true">
                          <div class="modal-dialog modal-sm">
                          <div class="modal-content">
                          <div class="modal-header" style="text-align:center">
                          <button type="button" class="close" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                          </button>
                          <h4 class="modal-title" id="modalLabelSmall">${title}</h4>
                          </div>
              
                          <div class="modal-body">
                          ${message}
                          </div>
                          <div class="modal-footer">
                          <button type="button" class="btn btn-default confirmButton">sure</button>
                          </div>
                          </div>
                          </div>
                          </div>
               `);
              
                //append confirm box to the DOM
                $("body").append(confirm);
                confirm.modal();
               //handlers
                      confirm.find("button.confirmButton").one("click",function(){
                          result(true);
                          confirm.modal("hide");
                      });
              
                      confirm.find("button.close").one("click",function(){
                          result(false);
                          confirm.modal("hide");
                      })
                      //remove modal after hiding it
                      confirm.one('hidden.bs.modal', function () {
                          confirm.remove();
                      });
              }
              
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 2014-05-03
                • 2017-01-19
                • 1970-01-01
                • 2017-09-10
                • 2011-06-08
                • 1970-01-01
                • 2012-03-10
                相关资源
                最近更新 更多