2015-12-20 90 views
-2

我試圖在執行我的Ajax調用後隱藏了input的父項,但由於某種原因它沒有工作,沒有發生效果,父項也未隱藏。ajax調用後執行jQuery函數時發生的問題

這裏是我的JQuery的片斷:

$(".getqty").mouseover(function() { 
    var split = this.id.split(":"); 
    var color = split[0]; 
    var size = split[1]; 
    var prodID = split[2]; 

    $.ajax({ //create an ajax request to loadstuff.php 
     type: 'POST', 
     url: 'includes/loadstuff.php',    
     dataType: 'html', //expect html to be returned 
     data:'color='+color+'&size='+size+'&prodID='+prodID,  
     success: function(response){     
      $(this).parent().hide(); //Problematic part 
     }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      alert(thrownError); 
     } 
    }); 
}); 

這是我的HTML:

<a href='#'> 
    <input class='getqty id='a:b:c' type='text'> 
</a> 

我試圖做的也許顯得毫無意義,但它實際上是我試圖理解爲什麼隱藏父項在懸停時不起作用。

但是我嘗試了以下並在ajax調用之前隱藏了父項並且它工作正常。我不明白爲什麼。

$(".getqty").mouseover(function() { 
    var split = this.id.split(":"); 
    var color = split[0]; 
    var size = split[1]; 
    var prodID = split[2]; 
    $(this).parent().hide(); //Moved it here and it works. But I need it after the ajax call 

$.ajax({ //create an ajax request to loadstuff.php 
    type: 'POST', 
    url: 'includes/loadstuff.php',    
    dataType: 'html', //expect html to be returned 
    data:'color='+color+'&size='+size+'&prodID='+prodID,  
    success: function(response){     

    }, 
    error:function (xhr, ajaxOptions, thrownError){ 
     alert(thrownError); 
    } 
}); 
}); 

回答

1

$(this)是原函數調用的外部移動。你可以給它一個變量,以便它連接到正確的選擇器。喜歡的東西:

$(".getqty").mouseover(function() { 
    var $this = $(this); 
    var split = this.id.split(":"); 
    var color = split[0]; 
    var size = split[1]; 
    var prodID = split[2]; 


    $.ajax({ //create an ajax request to loadstuff.php 
     type: 'POST', 
     url: 'includes/loadstuff.php',    
     dataType: 'html', //expect html to be returned 
     data:'color='+color+'&size='+size+'&prodID='+prodID,  
     success: function(response){     
      $this.parent().hide(); //Problematic part 
     }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      alert(thrownError); 
     } 
    }); 
}); 
0

$(this)指的是不同的對象:

success: function(response){     
    $(this).parent().hide(); //Problematic part 
}, 

因此改變你的代碼是這樣的:

$(".getqty").mouseover(function() { 
    var split = this.id.split(":"); 
    var color = split[0]; 
    var size = split[1]; 
    var prodID = split[2]; 
    var $this = $(this);          // Add this 

    $.ajax({ //create an ajax request to loadstuff.php 
     type: 'POST', 
     url: 'includes/loadstuff.php',    
     dataType: 'html', //expect html to be returned 
     data:'color='+color+'&size='+size+'&prodID='+prodID,  
     success: function(response){     
      $this.parent().hide();       // Change here. 
     }, 
     error:function (xhr, ajaxOptions, thrownError){ 
      alert(thrownError); 
     } 
    }); 
});