使用Twitter Bootstrap确认模态/对话框中的删除?

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

有没有办法使用Twitter Bootstrap模式对话框?

获取食谱

对于此任务,您可以使用已有的插件和引导扩展。 或者,您只需3行代码即可创建自己的确认弹出窗口。 看看这个。

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

 Delete record #23  

这里#confirm-delete指向HTML中的模式弹出div。 它应该有一个“OK”按钮配置如下:

  

现在你只需要这个小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; } 
      Delete "The first one", #23  

http://bootboxjs.com/ – 最新版本与Bootstrap 3.0.0一起使用

最简单的例子:

 bootbox.alert("Hello world!"); 

从网站:

该库公开了三种旨在模仿其原生JavaScript等价物的方法。 他们的确切方法签名是灵活的,因为每个都可以采用各种参数来自定义标签和指定默认值,但它们通常被称为如下:

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

这是一个实际的片段(点击下面的“运行代码片段”):

 $(function() { bootbox.alert("Hello world!"); }); 
       
  // ---------------------------------------------------------- Generic Confirm function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) { var confirmModal = $(''); 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); }); 

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

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(''); } $('#dataConfirmModal').find('.modal-body').text($(this).attr('data-confirm')); $('#dataConfirmOK').attr('href', href); $('#dataConfirmModal').modal({show:true}); return false; }); }); 

然后只要问任何问题/确认href:

 Delete 

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

感谢@ Jousby的解决方案 ,我设法让我的工作也工作,但发现我必须改进他的解决方案的Bootstrap模态标记,以使其正确渲染,如官方示例中所示 。

所以,这是我的通用confirm函数的修改版本,运行正常:

 /* Generic Confirm func */ function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) { var confirmModal = $(''); confirmModal.find('#okButton').click(function(event) { callback(); confirmModal.modal('hide'); }); confirmModal.modal('show'); }; /* END Generic Confirm func */ 

我觉得这很有用且易于使用,而且它看起来很漂亮: 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: ' Delete', confirmCallback: function (target) { //perform the deletion here, or leave this option //out to just follow link.. } }); 

我可以使用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 网站

以下解决方案比bootbox.js更好 ,因为

  • 它可以做bootbox.js可以做的一切;
  • 使用语法更简单
  • 它允许您使用“错误”,“警告”或“信息”优雅地控制邮件的颜色
  • Bootbox长986线,我的线只有110线

digimango.messagebox.js

 const dialogTemplate = '\ '; // 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'); } 

您可以使用回调函数尝试更多可重用的解决方案。 在此function中,您可以使用POST请求或某些逻辑。 使用过的库: JQuery 3>Bootstrap 3>

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

用于测试的Html代码:

 ...  Test Remove Action  ... 

使用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 = '
'; }; //---------------------------------------------------------------------------------------------------------------------- // 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'; };

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

confirmDelete.jsp

   

  

reusingPage.jsp

    <%@ include file="../some/path/confirmDelete.jsp" %> 

注意:这对删除请求使用http delete方法,您可以从javascript更改它,或者可以使用data-title或data-url等数据属性发送它,以支持任何请求。

如果你想用最简单的快捷方式来做,那么你可以用这个插件做到这一点


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


理念

我喜欢以这种方式自己实施 –

  1. 如果用户单击按钮上的s以从列表中删除项目,则JS调用将把项目ID (或任何更重要的数据)放在模式中的表单中。
  2. 然后在弹出窗口中,将有2个按钮用于确认。

    • 是的将提交表格(使用ajax或直接表格提交)
    • 不会只是解雇模态

代码将是这样的(使用Bootstrap ) –

     

This is a item to delete.

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

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

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

   

现在,使用它是直截了当的:

 Remove 

这里没有太大的改变,模态可以像这样包括:

 @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也被利用。

帮帮我,也许它可以帮助别人。

Interesting Posts