简体   繁体   English

jQuery this()似乎不起作用

[英]jQuery this() doesn't seem to work

I have this simple form & validation and everything works perfectly fine excepting 'this' points to, well, I have no idea what: 我有这个简单的形式和验证,一切都很好,除了'这'指向,好吧,我不知道什么:

$('#contact').validator().submit(function(e){
        e.preventDefault();
        $.ajax({
          type: "POST",
          url: this.action,
          data: { 
            mail: jQuery('input[name="mail"]').val(), 
            message: jQuery('textarea[name="message"]').val(),
          success: function(){
            $(this).hide();
          }
        }); 
    });

I want this code to hide #contact on success but this never happens. 我希望这段代码在成功时隐藏#contact,但这绝不会发生。

I tried to alert(this) , but I'm getting [object Object] , the same happened when I did console.log( $(this) ) (there's only Object with + next to it and when I click + I see all sorts of data excepting class / id of this element :( ). Any ideas? Is there something wrong with my code? 我试图alert(this) ,但我得到[object Object] ,当我执行console.log( $(this) )时发生了同样的事情(只有对象+旁边有+当我点击+我看到所有除了这个元素的类/ id之外的各种数据:()。任何想法?我的代码有什么问题吗?

You lose the context. 你失去了背景。 In submit function #contact element is the context. submit函数中, #contact元素是上下文。 In ajax callback ajax settings is the context. 在ajax回调中,ajax设置是上下文。

From jQuery Documentation: 来自jQuery文档:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; 所有回调中的this引用是在设置中传递给$ .ajax的context选项中的对象; if context is not specified, this is a reference to the Ajax settings themselves. 如果未指定context,则这是对Ajax设置本身的引用。

$('#contact').validator().submit(function (e) {
  e.preventDefault();

  var self = this;

  $.ajax({
    type: "POST",
    url: this.action,
    data: {
      mail: jQuery('input[name="mail"]').val(),
      message: jQuery('textarea[name="message"]').val(),
      success: function () {
        $(self).hide();
      }
    });
  });
});

this within the context of success method doesn't refer to the clicked element, you should cache the element: this范围内success方法并不指点击的元素,你应该缓存的元素:

$('#contact').validator().submit(function(e){
        e.preventDefault();
        var $this = $(this); // cache the object
        $.ajax({
          type: "POST",
          url: this.action,
          data: { 
            mail: jQuery('input[name="mail"]').val(), 
            message: jQuery('textarea[name="message"]').val()
          }, // missing }
          success: function(){
            $this.hide();
          }
        }); 
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM