2012-11-16 212 views
1

我似乎無法從$ .post部分訪問$(this)。它在它外面工作正常。下面是JavaScript的:

$('.idea').each(function(){ 
     var title = $(this).html(); 
     $.post("votes.php", { title: title }, function(data){ 
      $(this).nextAll('.voteTotal').html(data); 
     }, "json"); 
    }); 

HTML:

<h3 class="idea">Idea #1</h3> 
<h4 class="voteTotal"></h4> 
<p>This is a really cool idea.</p> 
<a href="#" class="vote">Click to vote</a> 
+0

S ee也是http://stackoverflow.com/questions/11297748/javascript-execution-context-of-function-argument/11297779#11297779 – Kos

+0

那麼你不是在'$ .post'內使用它,而是在一個匿名函數中被'$ .post'異步功能調用。 –

回答

4

你應該回調函數之前備份this

$(".idea").each(function() { 
    var $this = $(this), 
     title = $this.html(); 

    $.post("votes.php", { title: title }, function(data) { 
     $this.nextAll(".voteTotal").html(data); 
    }, "json"); 
}); 
+1

它不叫*備份*,而是自由變量*捕獲* ... –

0

使用context設置,然後它會工作:

$('.idea').each(function(){ 
    var title = $(this).html(); 
    $.post("votes.php", { title: title, context: this }, function(data){ 
     $(this).nextAll('.voteTotal').html(data); 
    }, "json"); 
}); 
相關問題