【问题标题】:$(this) object becomes undefined after a jquery post()$(this) 对象在 jquery post() 之后变得未定义
【发布时间】:2011-12-08 06:11:30
【问题描述】:

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

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

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

【问题讨论】:

  • 看看这个完全相同的副本:$(this) doesn't work in a function
  • 不要复制问题的答案,而是使用接受答案功能(在答案的左侧)标记有用的答案。

标签: jquery


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在您的示例中,这是指匿名函数。试试这个:

    $('.login-submit').live('click', function(){
    var that = this;
    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($(that).attr('class')); // THIS SAYS UNDEFINED
                // TRYING TO DO THIS
                $(that).siblings('.form-error').html(data['error']); 
            } 
        },'json');
    });
    

    然后,您的函数将 this 在其执行范围内,但是它将存储在 that 变量中。

    【讨论】:

      【解决方案3】:

      这是因为 Javascript 闭包——“this”在每个新函数的范围内重新定义。

      $('.login-submit').live('click', function(){
          alert($(this).attr('class')); // THIS WORKS
          var form = $(this).parent('form').get(0);   
          var values = $(this).parent('form').serialize();
          var me = $(this);
          $.post('/users/login',values,function(data){
              if(!data['success']) {
                  me.siblings('.form-error').html(data['error']); 
              } 
              },
          'json');
      });
      

      【讨论】:

        猜你喜欢
        • 2017-08-13
        • 2012-08-03
        • 2020-06-12
        • 2017-08-20
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        相关资源
        最近更新 更多