初始出现后,Bootstrap警报不会关闭

问题描述 投票:0回答:2

这是一个非常难以解释和演示的问题,基本上我使用的是PHP,Smarty,Ajax和Bootstrap的混合体。

我有一个带有Ajax表单的智能模板(这个工作),一个PHP后端,它将表单详细信息添加到数据库中(这也有效),成功或失败时会显示警报,此警报来自Bootstrap CSS,它被写入页面如下。

$('form').append('<div class="alert alert-success alert-dismissible" role="alert">' + data.message + '<a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a></div>');

警报会显示在页面中,警报会关闭!但是,例如,如果我或用户想要再次使用该表单,例如,要将另一条记录添加到数据库,警报会显示,但这次它永远不会关闭!因此,如果我添加另外10条记录并在每条记录之后单击提交按钮,我会在永不关闭的表单下面有10个警告框。

<script type="text/javascript">
    window.setTimeout(function() {
        $(".alert").fadeTo(1000, 0).slideUp(1000, function() {
            $(this).hide();
        });
    }, 5000);
</script>

有没有人知道我能做什么而不是可能有用?

以下代码关闭警报,但警报关闭时存在一些不一致。

$(document).ready(function() {
    $('form').submit(function(event) {

        // snip

        var alertTimer1 = window.setInterval(function() {
            if (typeof alertTimer2 === 'undefined') {
                var alertTimer2 = window.setTimeout(function() {
                    $('#alert').find('.alert').fadeTo(1000, 0).slideUp(1000, function() {
                        $(this).remove();

                        window.clearInterval(alertTimer1);
                        window.clearTimeout(alertTimer2);
                    });
                }, 5000);
            }
        }, 100);
    }
}
php jquery ajax bootstrap-4 smarty3
2个回答
0
投票

setTimeout函数只执行一次setInterval定期检查。例如:https://codepen.io/anon/pen/VGPYXB

更好的解决方案可能是在添加消息后添加警报消息集setTimeout函数或使用像delay这样的https://codepen.io/anon/pen/XPpJGe函数。


0
投票
  1. 使用$('.alert').alert()初始化警报
  2. $('.alert').alert('close')$('.alert').alert('dispose')关闭它

Bootstrap 3.3 Documentation - Alerts

Bootstrap 4.0 Documentation - Alerts

© www.soinside.com 2019 - 2024. All rights reserved.