jQuery:如何在AJAX回调中处理'this'

时间:2010-05-24 08:11:05

标签: jquery this

我目前的代码与此类似:

$('#some-form')
    .submit(function()
    {
        // Make sure we are not already busy
        if($(this).data('busy'))
            return false;
        $(this).data('busy', true);

        // Do post
        $.post("some/url", $(this).serialize(), function(data)
        {
            if(data.success) // Success is a boolean I set in the result on the server
            {
                // Deal with data
            }
            else
            {
                // Display error
            }

            $('#some-form')
                .removeData('busy');
        });
        return false;
    });

我的问题是我想以某种方式消除在post回调中知道表单id的需要。最后,我从表单中删除busy数据,我想以某种方式没有硬编码。有什么方法可以做到这一点吗?有没有办法可以将this中的任何内容交给帖子回调函数?因为我现在知道id,所以我可以通过做我已经做过的事来绕过它,但是我想知道如何不依赖于知道id,因为我经常没有id。 (例如,如果表中的每一行都有一个链接,并且所有行都具有相同的单击处理程序。

3 个答案:

答案 0 :(得分:2)

在创建回调之前设置一个值为“this”的变量。 然后在回调函数中使用该变量名。

var form = this;
$.post("some/url", $(this).serialize(), function(data) {
      $(form).removeData('busy');
}

这样,带有表单的变量将在回调中可用。 声明一个函数时,该函数可以访问同一作用域中的所有变量,即使它在声明的函数返回后被调用。

您可以在http://www.jibbering.com/faq/notes/closures/

详细了解闭包

答案 1 :(得分:0)

保留对表格的引用。

var form = $("form").submit(function ()
{
    // do ajax call here, referencencing the "form" variable

    return false; // return false to prevent default behavior
});

通常,您只需要处理一个表单元素。所以不需要在submit函数中创建引用,将this包装在jQuery对象中。

这是您修改后的代码:

var form = $("#some-form").submit(function ()
{
    if(form.data("busy")) return false;

    form.data("busy", true);

    $.post("some/url", form.serialize(), function (data)
    {
        if (data.success)
        {
        }
        else
        {
        }

        form.removeData("busy");
    });

    return false;
});

答案 2 :(得分:0)

使用bind

$('#some-form')
.submit(function()
{
    // Make sure we are not already busy
    if($(this).data('busy'))
        return false;
    $(this).data('busy', true);

    // Do post
    $.post("some/url", $(this).serialize(), function(data)
    {
        if(data.success) // Success is a boolean I set in the result on the server
        {
            // Deal with data
        }
        else
        {
            // Display error
        }


        $(this).removeData('busy');

    }.bind(this)); //Here
    return false;
});

你可以找到有关javascript范围的有趣文章: http://www.digital-web.com/articles/scope_in_javascript/ 只是google it