Bootstrap 5 个模态弹出窗口未从 JavaScript 激活

Bootstrap 5 modal popup not activating from JavaScript

我正在尝试以编程方式打开 bootstrap 5 模态,但代码执行时没有任何反应。

我的页面中包含 bootstrap.min.js, 我的页面中有一个 HTML 模态模板

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="exampleModalLabel">New message</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form>
                            <div class="mb-3">
                                <label for="recipient-name" class="col-form-label">Recipient:</label>
                                <input type="text" class="form-control" id="recipient-name">
                            </div>
                            <div class="mb-3">
                                <label for="message-text" class="col-form-label">Message:</label>
                                <textarea class="form-control" id="message-text"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        <button type="button" class="btn btn-primary">Send message</button>
                    </div>
                </div>
            </div>
        </div>

这是我写的javascript打开弹窗

var exampleModalPopup = new bootstrap.Modal(document.getElementById("exampleModal"), {});
            var modalTitle = exampleModalPopup.querySelector('.modal-title');
            var modalBodyInput = exampleModalPopup.querySelector('.modal-body input');
            modalTitle.textContent = 'An error has occurred';
            modalBodyInput.value = 'error';
            exampleModalPopup.modal();

模态弹出对象已创建,但没有任何反应,谁能告诉我哪里出错了?它在

处倒下
exampleModalPopup.querySelector('.modal-title');

根据 docs,为了通过 js show 模式,你可以这样做:

var exampleModalPopup = new bootstrap.Modal(document.getElementById("exampleModal"), {});
exampleModalPopup.show();

问题是您试图在 Bootstrap 模态对象上使用 querySelector(),而不是 DOM 对象。相反,像这样....

var exampleModal= document.getElementById("exampleModal");
var exampleModalPopup = new bootstrap.Modal(exampleModal, {});
var modalTitle = exampleModal.querySelector('.modal-title');
var modalBodyInput = exampleModal.querySelector('.modal-body input');
modalTitle.textContent = 'An error has occurred';
modalBodyInput.value = 'error';
exampleModalPopup.show();

Codeply

此外,使用 show() 方法,因为没有 modal() 方法。