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

编程入门 行业动态 更新时间:2024-10-15 22:24:35
本文介绍了$(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

本文发布于:2023-10-11 14:11:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   jquery   undefined   post

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!