首页 > 解决方案 > Bootstrap v5,如何在模态中传递变量(没有jquery)

问题描述

这是我的第一个问题 :-) 我正在尝试将变量传递到 Bootstrap v5 中的模式窗口中,可能不使用 jquery(v5 不再使用它)。

我有一个按钮:

<button class="btn btn-primary" id="sendMailButton">Send an Email</button>

此按钮触发功能“sendMailClicked”

document.getElementById("sendMailButton").addEventListener("click", sendMailClicked);

这就是功能

function sendMailClicked() {
   var theValue = document.getElementById('inputid').value;  
   var myModal = new bootstrap.Modal(document.getElementById('emailModal'), { backdrop: 'static' })
   myModal.show();
}

在 sendMailClicked 中定义了变量“theValue”并且它的值是正确的。我想在一个模态窗口中传递这个变量,它的内容应该是这样的:你的值是theValue

<div class="modal fade" id="emailModal" 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">Do you want to send an email?</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            Your value is <?= theValue ?>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                            <button type="button" class="btn btn-primary" id="yesSendMail" value="<?= theValue ?>">Ok invia</button>
                        </div>
                    </div>
                </div>
            </div>

我想在 HTML 中预加载的模态窗口是theValue未定义的原因。有没有办法将 value 值传递给模态窗口?理想的解决方案是不使用 jquery(不包含在 Bootstrap v5 中)。

标签: bootstrap-modalbootstrap-5

解决方案


您可以使用多种方法,但我猜最好的方法是在sendMailClicked函数内部的模态中定位孩子,然后将内部 html 设置为您想要的任何内容。

function sendMailClicked() {
   var theValue = document.getElementById('inputid').value;  
   var modalContainer = document.getElementById('emailModal')
   var myModal = new bootstrap.Modal(modalContainer, { backdrop: 'static' })
   
   modalContainer.querySelector(".modal-body").innerHTML = "Your value is: " + theValue;
   
   myModal.show();
}

推荐阅读