Bootstrap5远程模态框中Select2首次加载失效,二次加载正常
Bootstrap5模态框中Ajax加载的Select2首次点击不可见问题
问题背景
从Bootstrap3迁移至Bootstrap5后,模态框内的Select2组件出现异常。已知的两种常规解决方案均无效:
- 重写模态框的焦点强制方法:
$.fn.modal.Constructor.prototype.enforceFocus = function() {} - 为Select2设置
dropdownParent选项绑定到模态框
具体现象
通过Ajax加载包含模态框的内容并初始化Select2时:
- 首次点击触发链接,Select2完全不可见
- 关闭模态框后再次点击链接,Select2可正常显示
- 尝试移除
tabindex属性或设置tabindex='false',问题仍未解决
首次点击效果

二次点击效果

相关代码
HTML触发链接
<a href='url-to-controller-returning view' class='modal-remote'>Add</a>
Ajax加载逻辑代码
$(document).on('click', '.modal-remote', function (e) { e.preventDefault(); var $modalRemote = $('#modal-remote'), url = $(this).attr('href'); $.ajax({ url: url, beforeSend: function (data) { if (!$modalRemote.length) $modalRemote = $('<div class="modal fade" id="modal-remote" aria-hidden="true"><div class="modal-dialog ' + modalClass + '"><div class="modal-content"></div></div></div>'); $modalRemote.find('.modal-content').html('<div class="modal-header"><h5 id="remoteModalLabel">Loading...</h5><button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button></div><div class="modal-body"><div class="modal-remote-indicator"></div></div>'); $modalRemote.modal('show'); }, success: function (data) { $.fn.modal.Constructor.prototype._enforceFocus = function() {}; var $dom = $(document.createElement('html')); $dom[0].innerHTML = data; $dom.find('link').remove(); $modalRemote.find('.modal-header > h5').html($dom.find('title').text()); $modalRemote.find('.modal-body').html($dom.html()); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $modalRemote.find('.modal-header > h5').html('Error'); $modalRemote.find('.modal-body').html(XMLHttpRequest.responseText); } }); });
请问我忽略了什么?
内容的提问来源于stack exchange,提问作者Manoj Rai
相关产品推荐
相关产品推荐

