javascript - 无法通过淡入淡出关闭 Bootstrap 模态

标签 javascript jquery bootstrap-4 bootstrap-modal

我正在使用以下代码动态生成模式弹出窗口,但遇到了问题。问题是模式显示正确,但我无法关闭它。我尝试了 data-dismiss="modal".modal("hide") 但没有成功。我已经检查过按钮单击事件是否被触发,唯一的问题是模式没有关闭。

JS

// Requires jQuery
var dialogHelper = new dialog();

function dialog() {
    /* Bootstrap Modal Dialog
    *  Displays message from parameter
    */
    this.ShowModalDialog = function (message, title, buttons) {
        var dialogMessage = "";
        var dialogTitle = "System Message";
        var dialogButtons = [];

        if (message)
            dialogMessage = message;
        if (title)
            dialogTitle = title;
        if (buttons) {
            dialogButtons = buttons;
        }

        var id = randomString(10);

        jQuery("<div/>", {
            id: id,
            class: "modal fade",
            // href: 'http://google.com',
            //title: title,
            //rel: 'external',
            //text: message
        })
            .attr("tabindex", "-1")
            .attr("role", "dialog")
            .attr("aria-labelledby", id + "Label")
            .attr("aria-hidden", true)
            .attr("data-backdrop", "static")
            .attr("data-keyboard", false)
            .load("/Static/BootstrapDialogTemplate.html", function () {
                $("#" + id + " .modal-title")
                    .attr("id", id + "Label")
                    .text(dialogTitle);
                $("#" + id + " .modal-body").text(dialogMessage);

                var footer = $("#" + id + " .modal-footer");

                dialogButtons.forEach(function (element) {
                    $('<button/>', {
                        text: element.Text,
                        click: function () {
                            if (element.Event) {
                                element.Event();
                            }
                        },
                        class: element.Class
                    })
                        .attr("data-dismiss", "modal")
                        .appendTo(footer);
                });
            })
            .appendTo(document.body)
            .modal("show");
    };
};

/* Automatically destroy modal on close */
$(".modal").on('hidden.bs.modal', function () {
    $(this).data('bs.modal', null);
});

function randomString(length) {
    var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
    var string_length = length;
    var randomstring = '';

    for (var i = 0; i < string_length; i++) {
        var rnum = Math.floor(Math.random() * chars.length);
        randomstring += chars.substring(rnum, rnum + 1);
    }

    return randomstring;
};

/Static/BootstrapDialogTemplate.html

<div class="modal-dialog" role="document">
    <div class="modal-content">
        <div class="modal-header">
            <h5 class="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">
        </div>
    </div>
</div>

调用示例

dialogHelper.ShowModalDialog("Are you sure you want to create this item?", null, [{
        Text: "Yes",
        Event: function () { alert("YES!"); },
        Class: "btn btn-primary"
    }, {
        Text: "No",
        Event: function () { },
        Class: "btn btn-secondary"
    }]);

示例输出

<div id="2tF5r5mecT" class="modal fade show" tabindex="-1" role="dialog" aria-labelledby="2tF5r5mecTLabel" data-backdrop="static" data-keyboard="false" aria-modal="true" style="display: block;">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="2tF5r5mecTLabel">System Message</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
            </div>
            <div class="modal-body">Are you sure you want to create this item?</div>
            <div class="modal-footer">
            <button class="btn btn-primary" data-dismiss="modal">Yes</button><button class="btn btn-secondary" data-dismiss="modal">No</button></div>
        </div>
    </div>
</div>
<div class="modal-backdrop fade show"></div>

enter image description here

通过随机测试,我设法推断出在生成模态时删除 fade 类允许我在不进行任何其他更改的情况下关闭它。

来自

jQuery("<div/>", {
        id: id,
        class: "modal fade",
        // href: 'http://google.com',
        //title: title,
        //rel: 'external',
        //text: message
    })

jQuery("<div/>", {
        id: id,
        class: "modal",
        // href: 'http://google.com',
        //title: title,
        //rel: 'external',
        //text: message
    })

我的代码可以工作,但没有淡入淡出效果。我已经检查了所有自定义 CSS 的 .fade 但我没有。当问题仍然存在时,浏览器上不会出现控制台错误。你们有人遇到过这个问题吗?我刚刚升级到 JQuery 3.3.1 和 Bootstrap 4.2.1。当没有淡入淡出效果时,感觉很奇怪。

骗子

https://next.plnkr.co/edit/71QNigcwmUombEQ8?open=lib%2Fscript.js&preview

最佳答案

JQuery 的 .load()是异步的。 问题在于,当 .modal("show") 执行时,模态框的内容尚未加载。如果您修改代码以调用 .modal ("show") 在您传递给 .load() 的回调中,然后它就可以工作了。

我已经forked你的笨蛋,这样你就可以测试它。我将创建对话框元素并调用 .modal("show") 的代码更改为:

jQuery("<div/>", {
    id: id,
    class: "modal fade",
    // href: 'http://google.com',
    //title: title,
    //rel: 'external',
    //text: message
})
    .attr("tabindex", "-1")
    .attr("role", "dialog")
    .attr("aria-labelledby", id + "Label")
    .attr("aria-hidden", true)
    .attr("data-backdrop", "static")
    .attr("data-keyboard", false)
    .load("BootstrapDialogTemplate.html", function () {
        const $this = $(this);
        $this.find(".modal-title")
            .attr("id", id + "Label")
            .text(dialogTitle);
        $this.find(".modal-body", this).text(dialogMessage);

        var footer = $this.find(".modal-footer", this);

        dialogButtons.forEach(function (element) {
            $('<button/>', {
                text: element.Text,
                click: function () {
                    if (element.Event) {
                        element.Event();
                    }
                },
                class: element.Class
            })
                .attr("data-dismiss", "modal")
                .appendTo(footer);
        });
        $this.appendTo(document.body)
            .modal("show");
    });

主要变化是:

  1. .appendTo(document.body).modal("show"); 移至回调内部。

  2. 添加 const $this = $(this),然后使用 $this.find() 获取要修改的模板片段。

此时,读者会问“好吧,但是等等...为什么当 OP 不使用 fade 时它还能工作??”

这很复杂。基本事实是 Bootstrap 通常不适用于部分组件。当您调用告诉 Bootstrap 使用 DOM 元素作为 Bootstrap 组件的函数时,Bootstrap 关心的所有部分都需要存在。请注意,Bootstrap 不关心的那些位并不重要。您可以加载一段文本以异步方式放入模式主体中,或者加载一张图像,Bootstrap 可以很好地处理这些问题。它不关心这些事情。但是,当您异步加载采用 class="modal-dialog"div 时,您会遇到麻烦,因为这是 Bootstrap 用于提供行为的 DOM 结构的一部分组件。

在您的原始代码中,当创建模式时,this._dialog Modal 对象的字段获取值 null,因为 DOM 树中还没有匹配的元素。事实上,当你不使用fade时它似乎可以工作,这是偶然的。碰巧,当您使用 fade 时,代码路径会更多地使用 this._dialog,因此更容易受到 this._dialog 设置的干扰为null。当您不使用 fade 时,this._dialog 碰巧使用较少,并且它看起来工作得很好,但那是运气。我在没有fade的情况下追踪了执行路径,并看到了一些奇怪的事情发生。我预计将来会遇到问题。

最终,您希望在调用 .modal("show") 之前,对话框组件全部都存在于 DOM 中。

关于javascript - 无法通过淡入淡出关闭 Bootstrap 模态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54303246/

相关文章:

javascript - 如何将选中的头像存入数据库

鼠标悬停和鼠标按下时的 JavaScript 事件

javascript - Bootstrap 弹出窗口移动

javascript - 如何在单击时更改具有一个 id 的多个按钮类?

javascript - 如何使用jquery从输入字段模态 Bootstrap 获取值并将值显示到同一模态中的另一个输入字段?

javascript - 仅刷新数据表页面时如何清除状态

javascript - 如何从 child_process 中获取无缓冲或至少按顺序获取 stdout 和 stderr

javascript - 如何检查客户端是否下载了js文件

jquery - 使用 jquery 滚动时淡入和淡出

javascript - 在可编辑的 div 中检测动态创建的跨度上的退格