我的页面上有一个模态窗口,其内容会根据单击两个按钮中的哪一个而发生变化(<input />
的值发生变化)。为了更好地添加功能,我设置了一个额外的 block ,用于在出现错误时手动打开模态框。
为了确保表单是“粘性的”,我手动触发了 click
相应按钮上的事件,什么不是。但是,当我手动触发 click
事件,Bootstrap 没有添加 .modal-open
到 body 。由于我网站的构建方式,没有 .modal-open
在 body 上,Modal 完全隐藏在其他内容后面。
很明显我做错了什么,但我不知道。这是我的代码的副本:
<?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>
在进一步检查/取得进展后,我注意到我在页面上的其他地方以完全相同的方式手动触发模式/稍后,添加 .modal-open
没有任何问题。类到 body 。代码示例:
<script type="text/javascript">
function manualOpen(id) {
jQuery('button[data-id="'+id+'"]').trigger('click');
}
</script>
<button type="button" onclick="manualOpen(/*Correct id*/);">Open</button>
更多测试,我向页面添加了第二个模式,内容完全不同,在非常特定的情况下自动打开,它不需要根据按钮加载自定义内容 data-*
属性。如果第二个 Modal 没有某种形式的超时(如我对此问题的评论中所述),它也会遇到完全相同的问题。
最佳答案
使用 bootstrap 4,IMO 不使用超时的最佳方式是在模态的关闭事件中添加一个函数。
当一个模态正在关闭并且在它完成关闭操作之前有一个打开另一个模态的命令时,新模态是打开的但类 .modal-open 没有添加到主体中。
下一个函数打开模态检查是否有打开的模态。新的模式是直接打开的,或者根据情况在关闭事件回调中打开。此函数要求每个模态框都有一个 id。
function openModal(modalid) {
//Looks for current modal open
if ($('.modal.fade.show').length > 0) {
//Gets the id of the current opened modal
var currentOpenModalId = $('.modal.fade.show').attr('id');
//Attaches a function to the closing event
$('#' + currentOpenModalId).on('hidden.bs.modal', function () {
//Opens the new model when the closing completes
$('#' + modalid).modal('show');
//Unbinds the callback
$('#' + currentOpenModalId).off('hidden.bs.modal');
});
//Hides the current modal
$('#' + currentOpenModalId).modal('hide');
} else {
//If is not an opened modal, the new modal is opened directly
$('#' + modalid).modal('show');
}
}
关于javascript - 当通过 Javascript 触发时,Bootstrap Modal 不会向 body 添加 modal-open 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40023933/