使用 Twitter Bootstrap 如何在模态框中确认删除操作?

311

我有一张与数据库行关联的HTML表格。我想为每一行添加一个“删除行”链接,但是我希望在此之前先与用户确认。

是否可以使用Twitter Bootstrap模态框来实现这个功能?


5
http://jsfiddle.net/MjmVr/363/ - joni jones
3
看到这个问题,我想提出一个(在我看来)非常简单和更加直观的“修复”方法。我曾经苦于这个问题一段时间,然后意识到它可以如此简单:只需将实际的表单提交按钮放在模态对话框中,然后表单本身上的提交按钮什么也不做,只会触发对话框窗口……问题解决了。 - Michael Doleman
@jonijones 这个例子对我不起作用(第一个按钮点击后没有显示确认消息)- 在Chrome中测试过。 - egmfrs
13个回答

1
这是我为Bootstrap设计的确认框“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();
        });
}


1
你可以尝试使用回调函数来实现更多可重用的解决方案。在这个函数中,你可以使用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';
};

1
当涉及到一个相对较大的项目时,我们可能需要一些可重复使用的东西。这是我在 Stack Overflow 的帮助下提出的想法。

confirmDelete.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/>

reusingPage.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 删除方法进行删除请求,您可以通过 JavaScript 更改它,或者可以使用数据属性(如 data-title 或 data-url 等)将其发送以支持任何请求。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接