如何使用 jQuery 关闭对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6354443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:44:02  来源:igfitidea点击:

How do I close a dialog using jQuery?

jqueryjquery-uijquery-ui-dialog

提问by Shahin

I am using the code below to create a jQuery UI Dialog widget dynamically:

我正在使用下面的代码动态创建一个 jQuery UI 对话框小部件:

 $(function () {
        var Selector = $("a:contains('sometext')");
        $(Selector).bind('click', function () {
            var NewDialog = "<div dir=rtl id='MenuDialog'></div>";
            var DialogContetn = '<div dir=rtl ><table width=100%><tr><td><textarea id="txtRequestContent" cols="30" rows="2"></textarea></td><td><table><tr><td><input id="btnSendEditionRequest" type="button" value="Send" /></td></tr><tr><td><input id="btnCloseDialog" type="button" value="Cancel" /></td></tr></table></td></tr></table></div>';
            $('body').append(NewDialog);
            $('#MenuDialog').html(DialogContetn);
            $('#MenuDialog').hide();
            $('#MenuDialog').dialog({ modal: true, title: "title", show: 'clip', hide: 'clip' });
            $("#btnCloseDialog").live('click', function () {
                $("#MenuDialog").dialog('close');
            });
            return false;
        });
    });

First time it loads, the jQuery Dialog works correctly and when I click on the btnCloseDialog the jQuery Dialog closes successfully.

第一次加载时,jQuery 对话框工作正常,当我单击 btnCloseDialog 时,jQuery 对话框成功关闭。

However, after that, the btnCloseDialog no longer closes the dialog. Why is this happening?

但是,在那之后, btnCloseDialog 不再关闭对话框。为什么会这样?

Update

更新

I put my code out on a jsfiddle.

我把我的代码放在jsfiddle 上

This is strange behavior because the button closes the dialog properly in the jsFiddle, but not on the dialog in my project.

这是一种奇怪的行为,因为该按钮在 jsFiddle 中正确关闭了对话框,但不在我项目中的对话框上。

回答by évelyne Lachance

Because this shows up early in the search for creating a dynamic dialog in jquery, I'd like to point out a better method to do this. Instead of adding your dialog div and content to the HTML and then calling it, you can do this much more easily by shoving the HTML directly into a jquery object, as so:

因为这在 jquery 中搜索创建动态对话框的早期就出现了,所以我想指出一个更好的方法来做到这一点。无需将对话框 div 和内容添加到 HTML 然后调用它,您可以通过将 HTML 直接推入 jquery 对象来更轻松地完成此操作,如下所示:

$(function () {
    $("a:contains('sometext')").click(function() {
        var NewDialog = $('<div id="MenuDialog">\
            <p>This is your dialog content, which can be multiline and dynamic.</p>\
        </div>');
        NewDialog.dialog({
            modal: true,
            title: "title",
            show: 'clip',
            hide: 'clip',
            buttons: [
                {text: "Submit", click: function() {doSomething()}},
                {text: "Cancel", click: function() {$(this).dialog("close")}}
            ]
        });
        return false;
    });
});

I've also showed how you can put multiple buttons with inline functions, instead of attaching a live() function to the button. I've used this method in a couple of places and it works great for me. It also supports forms (I grabbed the data in doSomething() and submitted through ajax, but other methods work too), etc.

我还展示了如何使用内联函数放置多个按钮,而不是将 live() 函数附加到按钮上。我已经在几个地方使用过这种方法,它对我很有用。它还支持表单(我在 doSomething() 中抓取数据并通过 ajax 提交,但其他方法也可以)等。

回答by k?e?m?p? ?

You should probably not use ids for dynamically created content, as you could end up with more than one element with the same id - meaning that document.getElementById(which I assume sizzle uses for the #idselector) will only return the first (potentially non-visible) one.

您可能不应该将 id 用于动态创建的内容,因为您最终可能会得到多个具有相同 id 的元素 - 这意味着document.getElementById(我假设 sizzle 用于#id选择器)只会返回第一个(可能不可见)一个.

回答by rainabba

I needed a way to use a JSON webservice to control things like alerts and updates on the client-side without the client initiating an action. I hope to update this to use web-sockets, but for now it's a timed pull and each pull includes the delay for the next pull so I can even manage that once the client has loaded up my system.

我需要一种方法来使用 JSON 网络服务来控制客户端上的警报和更新等内容,而无需客户端启动操作。我希望更新它以使用网络套接字,但现在它是一个定时拉取,每次拉取都包括下一次拉取的延迟,因此一旦客户端加载我的系统,我什至可以管理它。

I'm also using show/expire and moment.js to filter by datetime and then using cookies with the id of each alert (not shown here) to prevent duplicate notices. This is coming along nicely and I might just decide to package it up as a library before too long if I get enough interest.

我还使用 show/expire 和 moment.js 按日期时间过滤,然后使用带有每个警报 ID(此处未显示)的 cookie 来防止重复通知。这进展顺利,如果我有足够的兴趣,我可能会决定在不久之后将其打包为一个库。

The bit specific to this question is 2 parts though; 1) JSON that includes the parameters for the jQuery.dialog() and 2) The code to use that JSON and create a dialog. The key here is to pay attention to how I'm referencing the 'n' object parameters and using them to create the dialog dynamically. The tDlg object is a big part of that as it is what ultimately represents the dialog and is passed into $().dialog()

这个问题的具体部分是 2 部分;1) 包含 jQuery.dialog() 参数的 JSON 和 2) 使用该 JSON 并创建对话框的代码。这里的关键是注意我如何引用“n”对象参数并使用它们来动态创建对话框。tDlg 对象是其中的重要组成部分,因为它最终代表对话框并传递给 $().dialog()

JSON Snippet that includes my dialog parameters:

包含我的对话框参数的 JSON 片段:

"doAlert":{
                "modal":false
                ,"height":240
                ,"width":380
                ,"title":"Welcome to the new BatchManager"
                ,"body":"<div style='text-align:center;'>Welcome to the new and enhanced<br/>BatchManager!</div><div style='text-align:center;'>Enjoy!</div>"
                ,"buttons":[
                    {
                        "text":"Ok"
                        ,"click":"$(this).dialog('close');"
                    }
                ]
            }

JavaScript snippet (using jQuery) to initialize a dialog based on my JSON (n corresponds with doAlert, which is part of an array of "notices" in this sample):

JavaScript 片段(使用 jQuery)根据我的 JSON 初始化对话框(n 对应于 doAlert,它是本示例中“通知”数组的一部分):

var tDlg = {
    resizable: false,
    height: (n.doAlert.height) ? n.doAlert.height : 240,
    width: (n.doAlert.width) ? n.doAlert.width : 240,
    modal: (n.doAlert.modal) ? n.doAlert.modal : true,
    dialogClass: "dlgFont"
};
if (n.doAlert.buttons) {
    tDlg.buttons = [];
    $.each(n.doAlert.buttons, function (i, n) {
            tDlg.buttons.push({
                            text: n.text,
                            click: new Function(n.click)
                    })
    })
}
$('<div class="dlgFont" title="' + n.doAlert.title + '"><p><span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 50px 0;"></span>' + n.doAlert.body + '</div>').dialog(tDlg);

回答by eugeneK

A few points to think about:

几点思考:

  1. OnDialogCloseyou should detach #MenuDialogfrom DOM to avoid multiple objects with same ID or you can check whether div#MenuDialogexists before adding one.

  2. var Selector = $("a:contains('sometext')");is a pointless line unless you re-use it else where.

  3. You use $('#MenuDialog')multiple times. It would be better to assign it to a variable instead of querying var Selector = $('#MenuDialog');all over again .

  1. OnDialogClose您应该#MenuDialog从 DOM分离以避免多个具有相同 ID 的对象,或者您可以div#MenuDialog在添加一个之前检查是否存在。

  2. var Selector = $("a:contains('sometext')");是一条毫无意义的线,除非你在其他地方重新使用它。

  3. $('#MenuDialog')多次使用。最好将它分配给一个变量而不是var Selector = $('#MenuDialog');重新查询。

回答by sekmo

Personally, I managed in this way:

就个人而言,我是这样管理的:

1) Build the html of the dialog, with two span with xxx as default value

1) 构建对话框的html,两个span,默认值为xxx

<div id="dialog1" title="Title of the dialog">
    <p>There are two variables: <span id="var1">xxx</span> and
    <span id="var2">xxx</span></p>
</div>

2) Make the div ready for being a dialog

2) 使 div 准备好成为一个对话框

$(function() {
    $( "#dialog1").dialog({
    autoOpen:false,
        modal: true,
        buttons: {
        "Button 1": function() {
            $(this).dialog( "close" );
        },
        "Button 2": function() {
            $(this).dialog( "close" );
        }
    }
    });
});

3) And modifying the value of the two spans with this function, before firing up the dialog:

3)并在启动对话框之前使用此函数修改两个跨度的值:

function showDialog(value1,value2){
    $("#var1").html(value1);
    $("#var2").html(value2);
    $( "#dialog1").dialog('open');
} 

4) So when you need it, call the function in this way

4)所以当你需要的时候,就这样调用函数

showDialog('tom','jerry'); 

You can try this at http://jsfiddle.net/sekmo/L46vb/1/

你可以在http://jsfiddle.net/sekmo/L46vb/1/试试这个