简体   繁体   English

无法关闭带有淡入淡出的Bootstrap模式

[英]Unable To Close Bootstrap Modal With Fade

I'm using the following code to dynamically generate my modal pop-ups but I encountered a problem. 我正在使用以下代码动态生成模式弹出窗口,但遇到了问题。 The problem is that the modal appears correctly but I am unable to close it. 问题是模式正确显示,但我无法将其关闭。 I've tried both data-dismiss="modal" and .modal("hide") with no avail. 我尝试了data-dismiss="modal".modal("hide")都无济于事。 I've checked that the button click event gets fired, the only problem is that the modal doesn't close. 我已经检查了按钮单击事件是否被触发,唯一的问题是模式没有关闭。

JS 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 /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>

Sample Call 样品电话

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"
    }]);

Sample Output 样本输出

<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>

在此处输入图片说明

Through random testing, I managed to deduce that removing the fade class when generating my modal allows me to close it without any other changes. 通过随机测试,我设法推断出,在生成模态时删除fade类可以使我关闭它而无需进行任何其他更改。

From

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

To

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

And my code works but without the fade effects. 而且我的代码有效,但是没有淡入淡出效果。 I've checked all my custom CSS for .fade but I don't have any. 我已经检查了所有自定义CSS的.fade但没有任何内容。 There are no console errors on the browser when the issue persist. 问题仍然存在时,浏览器上没有控制台错误。 Have any of you encountered this issue? 你们中有人遇到过这个问题吗? I've just upgraded to JQuery 3.3.1 and Bootstrap 4.2.1. 我刚刚升级到JQuery 3.3.1和Bootstrap 4.2.1。 It just feels weird when there is no fade effects. 没有淡入淡出效果时,感觉很奇怪。

PLUNKER PLUNKER

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

JQuery's .load() is asynchronous. jQuery的.load()是异步的。 The problem is that when .modal("show") executes, the contents of your modal are not loaded yet. 问题是当执行.modal("show") ,模态的内容尚未加载。 If you modify your code to call .modal("show") inside the callback you pass to .load() then it works. 如果您修改代码以在回调中调用.modal("show") ,则将其传递给.load()

I've forked your plunker so you can test it. 我已经分叉了您的矮人,所以您可以对其进行测试。 I changed the code that creates the dialog element and calls .modal("show") to this: 我更改了创建对话框元素的代码,并将此代码调用.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");
    });

The principal changes were: 主要更改为:

  1. Move .appendTo(document.body).modal("show"); 移动.appendTo(document.body).modal("show"); inside the callback. 在回调中。

  2. Add const $this = $(this) and then use $this.find() to get the pieces of the template to modify. 添加const $this = $(this) ,然后使用$this.find()获得要修改的模板片段。

And at this point, the reader asks "Ok, but wait... why is it working when the OP does not use fade ??" 此时,读者会问:“好吧,但是等等……为什么当OP不使用fade时,它可以工作?”

It's complicated. 情况很复杂。 The basic fact is that generally Bootstrap is not designed to work with partial components. 一个基本的事实是, 通常引导的目的不是与部分组件协同工作。 When you invoke a function that tells Bootstrap to use DOM elements as Bootstrap components, all the parts that Bootstrap cares about need to be present . 当您调用告诉Bootstrap使用DOM元素作为Bootstrap组件的函数时, Bootstrap关心的所有部分都必须存在 Note that those bits that Bootstrap does not care about don't matter. 请注意,Bootstrap无关的那些位无关紧要。 You could load a paragraph of text to put into the body of a modal asynchronously, or an image, and Bootstrap would work just fine with that. 您可以加载一段文本以异步方式放置到模式主体或图像中,Bootstrap可以很好地工作。 It does not care about these things. 它不在乎这些东西。 But when you load the div that takes class="modal-dialog" asynchronously you run into trouble because that's part of the structure of the DOM that Bootstrap uses to provide behavior to the component. 但是,当您异步加载采用class="modal-dialog"div ,就会遇到麻烦,因为这是Bootstrap用于向组件提供行为的DOM结构的一部分。

In your original code, when the modal is created, the this._dialog field of the Modal object gets the value null because there is not yet a matching element in the DOM tree. 在您的原始代码中,创建Modal ,由于DOM树中还没有匹配的元素,所以Modal对象的this._dialog字段将获得null值。 The fact that it seems to work when you do not use fade is happenstance. 当您不使用fade时似乎起作用的事实是偶然的。 It so happens that when you use fade the code path makes more use of this._dialog and is thus more disturbed by this._dialog being set to null . 碰巧的是,当您使用fade ,代码路径会更多地使用this._dialog ,因此this._dialog设置为null更加困扰。 When you do not use fade , this._dialog happens to be used less and it looks like it is working just fine but that's luck. 当您不使用fadethis._dialog碰巧被使用的更少了, 看起来它工作得很好,但是很幸运。 I've traced the execution path without fade and saw some bizarre stuff happening. 我已经跟踪了执行路径而不会fade并且看到了一些奇怪的事情发生。 I'd expect to run into problems down the road. 我希望将来会遇到问题。

Ultimately, you want your dialog component to be all present in the DOM before you call .modal("show") . 最终,您希望在调用.modal("show")之前,对话框组件在DOM中全部存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM