Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我试着在jQueryAjax中使用它_Jquery_Ajax - Fatal编程技术网

我试着在jQueryAjax中使用它

我试着在jQueryAjax中使用它,jquery,ajax,Jquery,Ajax,我意识到,$(this)在AJAX之外工作得很好,但在AJAX内部工作得不好,有人能帮我看看它有什么不对,或者我能做什么吗 $(函数(){ $(“.add_friend”)。每个(函数(){ var a=$(this.closest('div').find('#user').html(); $.post(“check_following.php”,{username:a},函数(resp){ if(resp==‘following’){ $(this.hide(); } }); });

我意识到,
$(this)
在AJAX之外工作得很好,但在AJAX内部工作得不好,有人能帮我看看它有什么不对,或者我能做什么吗

$(函数(){
$(“.add_friend”)。每个(函数(){
var a=$(this.closest('div').find('#user').html();
$.post(“check_following.php”,{username:a},函数(resp){
if(resp==‘following’){
$(this.hide();
}     
});
});
});

启动一个新函数时,
的上下文将发生变化。您必须以某种方式缓存该值。我通常在同样的情况下使用类似的方法:

$(函数(){
$(“.add_friend”)。每个(函数(){
var$this=$(this);//将其缓存在此处。
var a=$this.closest('div').find('#user').html();
$.post(“check_following.php”{
用户名:a
},功能(resp){
如果(resp==‘following’){
$this.hide();
}
});
});
});

这是一个范围问题,每次在jQuery中将一个函数放入另一个函数时,范围都不同

在第一级选择器$(“.add_-friend”).each(function(){..})中,您正在引用为选择器找到的每个迭代,在本例中是一个类为“.add_-friend”的元素

在第二层,在ajax调用中,$(this)不再包含元素引用。您需要将第一个级别的引用放在变量中,以便可以在另一个级别范围中使用

使用.text()方法而不是.html()也是一个好主意 因此,您只会在#user元素内获得文本,如果您在#user元素内放置一个“
”标记,选择器$this.closest('div')。find('#user').html();将返回“text
”,但如果每次只需要文本,则使用.text()更安全,还可以使用.trim()从字符串中删除任何empy空格

$(函数(){
$(“.add_friend”)。每个(函数(){
var$this=$(this);
var a=$this.closest('div').find('#user').text().trim();
$.post(“check_following.php”,{username:a},函数(resp){
if(resp==‘following’){
$this.hide();
}
});
});

});
此逻辑使我认为您在重复id
用户
。它成功了,非常感谢你,我很感激你。非常爱你。@atomty非常欢迎你。请考虑通过点击滴答键接受答案。提前谢谢。