开发者

Why does the Jquery dialog keep crashing on $(this)?

I am having a hell of a time trying to figure out why the code below crashes when the dialog is closed or cancelled. It errors on lines that use ($this) in the dialog button function.

For some reason if I hard code values into addTaskDialog.html(AddTaskForm); it works. I have even hardcoded the returned ajax form and it worked... This problem happens in all browsers.

  $(function ()
{

    /*
    *  Initializes AddTask Dialog (only needs to be done once!)
    */
    var $dialog = $('<div></div>').dialog(
{
    width: 580,
    height: 410,
    resizable: false,
    modal: true,
    autoOpen: false,
    title: 'Basic Dialog',
    buttons:
        {
            Cancel: function ()
            {
                $dialog.dialog('close');
            },
            'Create Task': function ()
            {

            }
        },
    close: function ()
    {
        $dialog.dialog('close');
    }
});


    /*
    * Click handler for dialog
    */
    $('#AddTask').click(function ()
    {

        /* Ajax request to load form into it */
        $.ajax({
            type: 'Get',
            url: '/Planner/Planner/LoadAddTaskForm',
            dataType: 'html',
            success: function (AddTaskForm)
            {
                $dialog.html(AddTaskForm);
                $dialog.dialog('open');
            }
        });
    });



});

}开发者_开发问答);


Ok I think I know what is going on. On your success callback you are referencing $(this) in AddTaskDialogOptions the problem is that the in this scope $(this) no longer refers to $("#AddTask") so you will need to set a variable to keep a reference to $(this) like so:

var that;
$('#AddTask').click(function ()
{
    that = $(this);
    /* Ajax request to load form into it */
    $.ajax({
        type: 'Get',
        url: '/Planner/Planner/LoadAddTaskForm',
        dataType: 'html',
        success: function (AddTaskForm)
        {
            var addTaskDialog = $('<div></div>');
            addTaskDialog.dialog(AddTaskDialogOptions);
            addTaskDialog.html(AddTaskForm);
            addTaskDialog.dialog('open');
        }
    });
});
var AddTaskDialogOptions = {
    width: 580,
    height: 410,
    resizable: false,
    modal: true,
    autoOpen: false,
    title: 'Basic Dialog',
    buttons:
        {
            Cancel: function ()
            {
                that.dialog('close');
            },
            'Create Task': function ()
            {

            }
        },
    close: function ()
    {
        that.dialog('destroy').remove();
    }
}


I figured it out. I'm not sure where I got this code, but it was causing the problems, so I took it out and it all works fine.

    close: function ()
{
    $dialog.dialog('close');
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜