11

在嵌套的 ajax 'success' 函数中引用 $(this) 时遇到问题...我知道这是一个范围问题,但似乎找不到在成功更新时关闭对话框的干净方法。谢谢你的帮助。

$("#dialog_support_option_form").dialog({
        width: 400,
        height: 180,
        bgiframe: true,
        autoOpen: false,
        modal: true,
        buttons: {
            'Save Support Option': function(){
                $.ajax({
                    type: 'POST',
                    url: "support_options/create_support_option.php",
                    data: $(this).find('form').serialize(),
                    success: function(data){
                        $("#list_support_options").html(data);
                        $(this).dialog('close');
                    }
                });
            },
            'Cancel': function(){
                $(this).dialog('close');
            }
        },
        close: function(){
            $(this).find('input').val('');
        }
    });
4

3 回答 3

21

您应该使用 ajax 选项context: $(this),将回调范围设置为选定元素。

于 2010-04-06T14:53:58.963 回答
4

您需要拥有该变量的副本,如下所示:

var dlg = $(this);
$.ajax({
   type: 'POST',
   url: "support_options/create_support_option.php",
   data: $(this).find('form').serialize(),
   success: function(data){
     $("#list_support_options").html(data);
     dlg.dialog('close');
   }
});

由于this返回时处于不同的上下文中,因此您需要捕获它并将其传递给闭包:)

于 2010-04-06T14:50:53.657 回答
2

试试看$.proxy()

success: $.proxy(function(data){
   $(this).dialog('close');
}, this);

您可以将范围从“上方”“传递”到带有它的函数

于 2010-04-06T14:51:01.207 回答