$(this)对象在jquery post()后变为undefined [英] $(this) object becomes undefined after a jquery post()

查看:122
本文介绍了$(this)对象在jquery post()后变为undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On the login page of my site I have two identical login forms. One is in the main body of the page and the 2nd one is loaded into a jquery dialog for the Login link in the header. I have already removed all identical ID's and used class instead.

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

What I am trying to do is: after user clicks submit in the dialog, I am trying to put the error msg in the right DIV but I get undefined for $(this) after the jquery post() or ajax call.

$('.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');
});

以下是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>


推荐答案

帖子回调在不同的上下文中执行。

The post callback is executed in a different context.

你需要在变量中保存外部这个所以你可以在内部函数中使用它。

You need to save the outer this in a variable so you can use it in the inner function.

这篇关于$(this)对象在jquery post()后变为undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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