4

我正在创建一个用户信息编辑对话框,该对话框使用获取编辑用户信息,$.post但由于未使用任何 HTML 元素初始化对话框,因此我无法关闭此对话框。

我正在尝试$('#editUser').dialog('close'),但它不会工作。

这是主体:

<div id='userInfo'>
<div class='user'>
    <span class='userId'>1</span>
    <span class='userName'>John</span>
</div>
<div class='user'>
    <span class='userId'>2</span>
    <span class='userName'>Jane</span>
</div>

这是用于创建对话框的脚本:

$(function() {
$('.user').click(function() {
     var uid = $(this).find('span.userId').html();
    $post('/e-val/user/edit.php', {id: uid}, function(html) {
       $(html).dialog();
    });
});

$('body').on('click', '#closeEditDialog', function() {
   $('#editUser').dialog('close')
});
});

对话框按预期打开,但没有按预期关闭。

这是 ajax 脚本返回的对话框的 HTML。

<div id='editUser'>
<table>
    <tr>
        <td>Username</td>
        <td><?php echo $user['name'] ?></td>
    </tr>
    <tr>
        <td>Email</td>
        <td><?php echo $user['email'] ?></td>
    </tr>
    <tr>
        <td colspan='2'>
<input type='button' id='closeEditDialog' value='close' />
</td>
    </tr>
</table>
</div>

我该怎么做才能关闭它?我可以$('#editUser').remove()用来删除对话框,但我需要关闭它而不是删除它。

4

3 回答 3

2
var mydialog;
$(function() {
$('.user').click(function() {
     var uid = $(this).find('span.userId').html();
    $post('/e-val/user/edit.php', {id: uid}, function(html) {
       mydialog = $(html);
       mydialog.appendTo('body');
       mydialog.dialog();
    });
});

$('body').on('click', '#closeEditDialog', function() {
   mydialog.dialog('close')
});
});
于 2012-08-10T12:56:02.653 回答
2

在创建对话框之前,您可能需要将该 html 插入到您的 DOM 中。

$("body").append(html);
$("#editUser").dialog();

好吧,至少如果您的对话框以这种方式显示,没有什么可以阻止它关闭,您使用的是相同的选择器。

EDIT

Also, do not forget that .dialog() will initialize the widget, try not calling it more than once. Using .dialog("open") instead.

Best would be even to already add the dialog's div into your html, and then append your server side code in it to dynamically update the content of the dialog.

于 2012-08-10T13:12:15.360 回答
1

$('#editUser').dialog('close') won't work because you've never used $('#editUser') to initialize the dialog, so you cannot use it either to close it, You need to use the same handler that was used to create it.

As answered here by Gil & Trinh : Just add the dialog content to the DOM first and then initialize the dialog:

$post('/e-val/user/edit.php', {id: uid}, function(html) {
   $(html).appendTo('body');
   $('#editUser').dialog( {autoOpen: false} );
});

autoOpen: false will prevent the dialog from opening by itself and it can be opened using $('#editUser').dialog('open') anytime.

于 2012-08-11T03:06:20.293 回答