在执行Ajax调用后,我试图隐藏input
的父级,但由于某种原因,它不起作用,即没有效果,父级也没有隐藏。
这是我的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);
}
});
});
$(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);
}
});
});
$(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);
}
});
});