簡體   English   中英

jQuery this()似乎不起作用

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

我有這個簡單的形式和驗證,一切都很好,除了'這'指向,好吧,我不知道什么:

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

我希望這段代碼在成功時隱藏#contact,但這絕不會發生。

我試圖alert(this) ,但我得到[object Object] ,當我執行console.log( $(this) )時發生了同樣的事情(只有對象+旁邊有+當我點擊+我看到所有除了這個元素的類/ id之外的各種數據:()。任何想法?我的代碼有什么問題嗎?

你失去了背景。 submit函數中, #contact元素是上下文。 在ajax回調中,ajax設置是上下文。

來自jQuery文檔:

所有回調中的this引用是在設置中傳遞給$ .ajax的context選項中的對象; 如果未指定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范圍內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