如何在$ .ajax的成功回调中传递$(this) [英] How to pass $(this) in success callback of $.ajax

查看:190
本文介绍了如何在$ .ajax的成功回调中传递$(this)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到访问$(this)的一些不同示例是ajax的成功回调,但是没有一个给我我想要的答案-他们都在ajax函数中访问$(this),我想传递$(this )到一个单独的功能.

I have seen a few different examples of accessing $(this) is the success callback of ajax but none give me the answer I want - they all access $(this) within the ajax function, I want to pass $(this) to a separate function.

所以如果有两个文本框需要验证

So if there are 2 textboxes that need to be validated

$("#tb1").focusout(function(){
    $.ajax({
        type:'POST',
        url: 'validURL',
        data: {various_parameters},
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        success: function(data){
            validInput(data, $(this));
        },
        error: error
    });
}

$("#tb2").focusout(function(){
    $.ajax({
        type:'POST',
        url: 'validURL',
        data: {various_parameters},
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        success: function(data){
            validInput(data, $(this));
        },
        error: error
    });
}

function validInput(response, obj){
    console.log(response.d);
    console.log(obj.val());
};

当我运行代码时,我得到了response.d的正确值,但出现了一个错误:jquery-1.11.1.min.js:4 Uncaught TypeError:无法读取obj.val()的undefined属性"toLowerCase".

When I run the code I get the correct value for response.d but an error : jquery-1.11.1.min.js:4 Uncaught TypeError: Cannot read property 'toLowerCase' of undefined for obj.val().

我做错什么了吗?

感谢您的帮助. 请参阅:执行/运行

Thanks for any help. See:Dos/Run

推荐答案

$(this)是相对于最内层函数的,在这种情况下,您需要在ajax查询之前将$(this)分配给变量,并在成功中使用该变量.

$(this) is relative to the inner-most function, and in this case you'll need to assign $(this) to a variable before the ajax query, and use that variable in the success instead.

$("#tb1").focusout(function(){
    var elem = $(this);
    $.ajax({
        type:'POST',
        url: 'validURL',
        data: {various_parameters},
        contentType: 'application/json; charset=utf-8',
        dataType:'json',
        success: function(data){
            validInput(data, elem);
        },
        error: error
    });
}

这篇关于如何在$ .ajax的成功回调中传递$(this)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆