简体   繁体   中英

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.

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?

You lose the context. In submit function #contact element is the context. In ajax callback ajax settings is the context.

From jQuery Documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

$('#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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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