【问题标题】:Open a Bootstrap modal via a plain function not a jQuery object method call通过普通函数而不是 jQuery 对象方法调用打开 Bootstrap 模式
【发布时间】:2021-07-14 05:06:41
【问题描述】:

我可以通过 jQuery 对象上的 方法 打开 Bootstrap 的 modal dialogs

$('#myModal').modal(options)

但是在我的代码中,我已经将模态 div 的普通 DOM Element 检索为

var myModal = document.querySelector("#myModal")

但是这个Element 对象没有Bootstrap 的modal 方法。有没有办法使用这个 Element 对象和 not 来调用 jQuery 选择器?那么是否可以将 Bootstrap 的 modal 代码作为普通的 function 以 Element 作为参数来调用?我正在考虑类似的事情

modal(myModal, options)

任何指针都非常感谢!

【问题讨论】:

    标签: javascript jquery twitter-bootstrap bootstrap-4 bootstrap-modal


    【解决方案1】:

    没有办法像 modal(myModal, options) 那样做,因为 Bootstrap(像所有插件一样)扩展了 jQuery 函数原型。

    当 Bootstrap 的 JavaScript 首次运行时,它使用类似于 $.fn.modal 的代码扩展 jQuery 的原型函数,然后 Bootstrap 将模态功能分配给新的 jQuery 函数。

    现在,如果您已经将模态元素分配给 JavaScript 变量,则可以将该变量用作 jQuery 选择器并显示、切换或隐藏或任何您想要的操作。我不知道这样做是否有任何好处,但这是可能的。

    在下面的演示中,我使用 JavaScript 在页面加载时打开一个模式:

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="myModalLabel">Modal title</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    ...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary">Save changes</button>
                </div>
            </div>
        </div>
    </div>
    
    <script>
        const myModalElement = document.getElementById('myModal');
    
        $(myModalElement).modal('show');
    
        /* $('#myModal').modal('show'); */
    </script>

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-11
      • 1970-01-01
      相关资源
      最近更新 更多