$(this)对象在jquery post()后变为undefined

use*_*509 2 jquery

在我的网站的登录页面上,我有两个相同的登录表单.一个在页面的主体中,第二个被加载到标题中的Login链接的jquery对话框中.我已经删除了所有相同的ID并使用了类.

我想要做的是:用户在对话框中单击提交后,我试图将错误消息放入正确的DIV中,但$(this)在jquery post()或ajax调用之后我得到了未定义.

$('.login-submit').live('click', function(){
alert($(this).attr('class')); // THIS WORKS
    var form = $(this).parent('form').get(0);   
    var values = $(this).parent('form').serialize();
    $.post('/users/login',values,function(data){
        if(!data['success']) {
            alert($(this).attr('class')); // THIS SAYS UNDEFINED
            // TRYING TO DO THIS
            $(this).siblings('.form-error').html(data['error']); 
        } 
    },'json');
});
Run Code Online (Sandbox Code Playgroud)

这是HTML:

<form class="form-login" method="post" action="/users/login">
<input type="hidden" name="_method" value="POST">
<div class="form-error"></div>
<input name="data[User][username]" type="text" maxlength="20" id="UserUsername">
<input type="button" class="login-submit" value="Sign In">
</form>
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 5

post回调是在不同的上下文中执行.

您需要将外部保存this在变量中,以便可以在内部函数中使用它.