如何使用jQuery关闭对话框?

时间:2021-02-09 23:56:25

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

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

 $(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 Dialog正常工作,当我点击btnCloseDialog时,jQuery Dialog成功关闭。

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中正确关闭了对话框,但在我的项目中没有关闭对话框。

5 个解决方案

#1


42  

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提交,但其他方法也有效),等等。

#2


3  

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 #id selector) will only return the first (potentially non-visible) one.

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

#3


2  

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 Web服务来控制客户端的警报和更新等事情,而无需客户端启动操作。我希望更新它以使用网络套接字,但是现在它是一个定时拉动,每次拉动包括下一次拉动的延迟,所以我甚至可以管理一旦客户端加载我的系统。

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

#4


1  

A few points to think about:

要考虑以下几点:

  1. OnDialogClose you should detach #MenuDialog from DOM to avoid multiple objects with same ID or you can check whether div#MenuDialog exists before adding one.

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

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

    var Selector = $(“a:contains('sometext')”);除非你在其他地方重新使用它,否则它是毫无意义的。

  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 .

    你多次使用$('#MenuDialog')。最好将它分配给变量而不是查询var Selector = $('#MenuDialog');一遍又一遍。

#5


1  

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/试试这个

#1


42  

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提交,但其他方法也有效),等等。

#2


3  

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 #id selector) will only return the first (potentially non-visible) one.

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

#3


2  

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 Web服务来控制客户端的警报和更新等事情,而无需客户端启动操作。我希望更新它以使用网络套接字,但是现在它是一个定时拉动,每次拉动包括下一次拉动的延迟,所以我甚至可以管理一旦客户端加载我的系统。

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

#4


1  

A few points to think about:

要考虑以下几点:

  1. OnDialogClose you should detach #MenuDialog from DOM to avoid multiple objects with same ID or you can check whether div#MenuDialog exists before adding one.

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

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

    var Selector = $(“a:contains('sometext')”);除非你在其他地方重新使用它,否则它是毫无意义的。

  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 .

    你多次使用$('#MenuDialog')。最好将它分配给变量而不是查询var Selector = $('#MenuDialog');一遍又一遍。

#5


1  

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/试试这个