如何在关闭时清除Bootstrap远程模态内容?

时间:2016-09-06 23:21:44

标签: javascript jquery twitter-bootstrap

我正在启动一个带有远程内容的模式(但在同一个域上)。模式可以在同一页面上使用不同内容多次打开,因此当它关闭时,我需要clear .modal-body部分。

我试着这样做:

function close_modal()

{

    $('.modal').modal('hide');

    $('body').on('hidden.bs.modal', '.modal', function () {
        $(this).removeData('bs.modal');
    });


}

但由于某种原因,当我打开另一个模态目标时,之前的内容仍然可见一瞬间。我还检查了源代码,之前加载的内容仍然存在。我该如何解决?这是我的标记:

$('a[rel=modal]').on('click', function(evt) {
    evt.preventDefault();
    var modal = $('#modal').modal();
    modal
        .find('.modal-body')
        .load($(this).attr('href'), function (responseText, textStatus) {
            if ( textStatus === 'success' || 
                 textStatus === 'notmodified') 
            {
                modal.show();
            }
    });
});

和HTML:

<div id="modal" class="modal fade" 
     tabindex="-1" role="dialog" aria-labelledby="plan-info" aria-hidden="true">
    <div class="modal-dialog modal-full-screen">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" 
                  data-dismiss="modal" aria-hidden="true">
                  <span class="glyphicon glyphicon-remove-circle"></span>
                </button>
            </div>
            <div class="modal-body">
                <!-- /# content goes here -->
            </div>
        </div>
    </div>
</div>

3 个答案:

答案 0 :(得分:2)

您应该能够使用jQuery的empty方法从.modal-body中删除所有子节点:

$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).find('.modal-body').empty();
});

答案 1 :(得分:2)

有一个问题是,在你关闭它之前,你不是在听关闭。你有:

// Hide the modal
$('.modal').modal('hide');

// Start listening for the hide event, if the modal closes remove the data
$('body').on('hidden.bs.modal', '.modal', function () {
    $(this).removeData('bs.modal');
});

相反移动移动隐藏侦听器,使其在隐藏事件之前运行(可能在函数外部,因为它只需要开始侦听一次)或删除它,只需要$('.modal').removeData('bs.modal');

答案 2 :(得分:2)

假设你的模态没有做任何特殊的事情,你可能会发现使用像Bootbox.js这样的东西更容易,它可以动态生成你的Bootstrap模态。您的代码看起来像:

$('a[rel=modal]').on('click', function(evt) {
    evt.preventDefault();

    var url = $(this).attr('href');

    $.get(url)
        .done(function (response, status, jqxhr) {
            // store a reference to the bootbox object
            var dialog = bootbox.dialog({
                message: response
            });
        })
        .fail(function(jqxhr, status, error){
            /* Do something when the form can't be loaded */
        });
});
相关问题