2009-12-17 160 views
0

嘿,我試圖改變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

回答

6

這可能是因爲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); 
     } 
     } 
); 
}); 
0

它可能有一些做與this不是代表$(".home .up_0")元素,因爲它是function(data){}成功函數內?

嘗試添加虛擬DIV ID =「測試」,併成功使用功能裏面:

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

這會告訴你,如果它的工作。如果是這樣,你需要使用var來存儲this所代表的內容。

1

您的問題是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); 
      } 
     }); 
});