通过 Javascript 触发时,Bootstrap Modal 不会将模态开放类添加到主体中

Cha*_*xmk 6 javascript jquery twitter-bootstrap

我的页面上有一个模态框,其内容根据单击两个按钮中的哪一个而变化( an<input />的值发生变化)。为了更好地添加功能,我设置了一个附加块,如果有错误显示,该块应该手动打开模态框。

为了确保表单“粘性”,我手动触发click相应按钮上的事件等等。但是,当我手动触发该click事件时,Bootstrap 不会添加.modal-open到正文中。由于我的网站是如何构建的,没有.modal-open在正文上,模态框完全隐藏在其他内容后面。

显然我做错了什么,但我不知道。这是我的代码的副本:

<?php
$modalerror = false;
$id = 0;
if (/*Basic check for errors*/) {
    $modalerror = true;
    $id = /*Get the correct id*/;
}
?>
<script type="text/javascript">
    jQuery( document ).ready(function($) {
        $('#modal').on('show.bs.modal', function(event) {
            var button = $(event.relatedTarget);

            if (button.attr('data-name') && button.attr('data-name') != '') {
                $('#name').val(button.attr('data-name'));
            } else {
                $('#name').val('');
            }
        });
    });

    <?php if ($modalerror) { ?>
        jQuery ( window ).load(function() {
            jQuery('button[data-id=<?php echo $id; ?>]').trigger('click');
        });
    <?php } ?>
</script>
Run Code Online (Sandbox Code Playgroud)

.modal-open经过进一步检查/进展,我注意到我在页面其他地方以完全相同的方式手动触发模态/稍后,将类添加到主体中没有任何问题。代码示例:

<script type="text/javascript">
    function manualOpen(id) {
        jQuery('button[data-id="'+id+'"]').trigger('click');
    }
</script>
<button type="button" onclick="manualOpen(/*Correct id*/);">Open</button>
Run Code Online (Sandbox Code Playgroud)

甚至更多的测试,我向页面添加了第二个模式,其内容完全不同,在非常特定的情况下自动打开,它不需要根据按钮属性加载自定义内容data-*。如果第二个模态没有某种形式的超时(正如我对此问题的评论中提到的),它也会遇到完全相同的问题。

小智 0

我正在使用 Bootstrap 4.1.1 和 jQuery 3.3.1,并遇到了同样的问题。50ms并没有解决问题。所以,我必须将其提高到 500 毫秒,结果成功了!

//hide first
$('#modal1').modal('hide');
//add delay when showing next modal
setTimeout(function () {
  $('#modal2').modal('show');
}, 500);
Run Code Online (Sandbox Code Playgroud)