jquery ajax将无法正常工作

问题描述:

嘿,我试图改变ajax请求后,ajax请求的作品的div的html。数据是正确的,但可以选择不似乎找到了DIVjquery ajax将无法正常工作

这里的代码

$(".home .up_0").click(function(){ 
    $.post("includes/vote.php", 
     { 
     truc : $(this).attr("id") 
     }, 
     function(data){ 
     if(data=='fail') 
     { 
      alert("Error."); 
     } 
     else 
     { 
      $(this).parents('.home').find('.score_neutre').html(data); 
     } 
     } 
); 
}); 
+0

我们需要看到一些HTML代码弄清楚为什么它不工作。 – 2009-12-17 16:19:34

+0

你能发布相应的HTML代码吗? – 2009-12-17 16:19:50

+1

'this'可能不存在于回调函数中。在JQuery中这肯定有一个解决方法,但我不知道它叫什么。 – 2009-12-17 16:22:31

这可能是因为this是不是你所期望的内部函数中的东西。你将需要添加一个变量来存储参考:

$(".home .up_0").click(function(){ 
    var this_obj = $(this); 
    $.post("includes/vote.php", 
     { 
     truc : $(this).attr("id") 
     }, 
     function(data){ 
     if(data=='fail') 
     { 
      alert("Error."); 
     } 
     else 
     { 
      this_obj.parents('.home').find('.score_neutre').html(data); 
     } 
     } 
); 
}); 

它可能有一些做与this不是代表$(".home .up_0")元素,因为它是function(data){}成功函数内?

尝试添加虚拟DIV ID =“测试”,并成功使用功能里面:

£('#Test').html(data); 

这会告诉你,如果它的工作。如果是这样,你需要使用var来存储this所代表的内容。

您的问题是this没有指向你的想法。

这样做:

$(".home .up_0").click(function(){ 
    var $this = $(this); // Cache the current `this` as a jQuery wrapped DOM element 
    $.post("includes/vote.php", 
     { truc : $(this).attr("id") }, 
     function(data){ 
      if(data=='fail') { 
       alert("Error."); 
      } else { 
       // Reference the cached variable `$this` 
       $this.parents('.home').find('.score_neutre').html(data); 
      } 
     }); 
});