【问题标题】:Bootstrap 4 Modal as Confirm RevisitedBootstrap 4 模态作为确认重新访问
【发布时间】:2019-11-28 17:06:47
【问题描述】:

我想用 Bootstrap 4 制作一个“灵活”的确认对话框,因为我不想单独对每个确认模式/动作进行硬编码。

所以,使用标准的模态

<div class="modal fade" tabindex="-1" role="dialog" id="msgModal">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="msgModalTitle">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="msgModalBody">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Doch nicht</button>
                <button type="button" class="btn btn-primary" id="btnModelConfirmMessage">OK</button>
            </div>
        </div>
    </div>
</div>

以及相应的 js-magic :D

function showConfirm(htmlInput,headerTxt, fun){
    $('#msgModalTitle').text(headerTxt);
    $('#msgModalBody').html(htmlInput);
    $('#msgModal').modal('show');
    $('#btnModelConfirmMessage').click(function () {
        fun();
        $('#msgModal').modal('hide');
    });
}

我认为,通过将“动作”部分作为函数发送,一旦单击“确定”按钮 #btnModelConfirmMessage 就会执行。

像一个魅力,但它有一个重大错误。

似乎事件处理程序停留在模式上,即如果我显示并隐藏模式,确定按钮将触发该功能两次。

我发现了这篇文章 Bootstrap modal firing up incrementing times 它建议将 click() 事件移到外面。我确信这将适用于该特定任务,但是我会失去该功能。

那么如何使用hide.bs.modal 事件解除处理程序的绑定?

【问题讨论】:

    标签: javascript jquery twitter-bootstrap bootstrap-modal


    【解决方案1】:

    阅读 jquery-doc 后,答案相当简单:

    变化:

    $('#btnModelConfirmMessage').on('click',function () {
            fun();
            $('#msgModal').modal('hide');
    });
    

    然后在 hide.bs.modal 事件上添加一个新调用

    $('#msgModal').on('hide.bs.modal',function () {
            $('#btnModelConfirmMessage').off();
    });
    

    这会移除之前添加的处理程序,因此我们不会堆叠事件。

    希望有人会发现这很有用:))

    干杯, 丹尼尔

    【讨论】:

      猜你喜欢
      • 2016-04-30
      • 2020-12-20
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2018-09-11
      • 1970-01-01
      • 2015-02-07
      • 1970-01-01
      相关资源
      最近更新 更多