如何延迟加载Boostrap模式,直到加载远程内容

How do I delay the loading of a Boostrap modal until the remote content is loaded?

本文关键字:加载 程内容 延迟加载 Boostrap 模式      更新时间:2023-09-26

我正在远程加载内容:

$('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();
            }
    });
});

问题是,模态显示和1-2秒后的内容显示和扩展模态,所以它是一种"跳跃"。是否有一种方法可以延迟模态的加载,直到收到内容之后?

在您发出请求之前,$('#modal').modal();正在显示您的模式。您应该在.load()的回调函数中显示模态,该函数在请求完成后触发。以下是你如何在对代码做最小修改的情况下使它工作的方法:

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

注意我从jquery对象中删除了.modal()调用,然后我使用modal.modal("show"),这可能是你想做的(而不是.show())