2009-11-17 18 views
1

我需要進行Ajax調用並讓響應更新被點擊的DOM元素的子元素以觸發事件。樣本HTML:如何在Ajax調用中保留上下文

<div class="divClass"> 
    <p class="pClass1">1</p> 
    <p class="pClass2">Some text.</p> 
</div> 
<div class="divClass"> 
    <p class="pClass1">2</p> 
    <p class="pClass2">Some text.</p> 
</div> 
<div class="divClass"> 
    <p class="pClass1">3</p> 
    <p class="pClass2">Some text.</p> 
</div> 

樣品javascript代碼:

$(document).ready(function(){ 
    $(".divClass").each(
     function(e) { 
      $(this).attr('divValue', $('p.pClass1', this).text()); 
      $('p.pClass1', this).text('?'); 

      $(this).click(function(e) { 
       e.preventDefault(); 

       $.ajax({ 
        type: "POST", 
        url: "ajax.php", 
        data: "val=" + $(this).attr('divValue'), 
        success: function(msg) { 
         myData = JSON.parse(msg); 
         $('p.pClass1', this).html(myData.results[0]); // problem exists here 
        } 
       }); 
      }); 
     } 
    ); 
}); 

在問題行 「這」 指的是Ajax響應對象。我不知道如何保留上面幾行的「this」上下文,所以我可以用Ajax調用的響應來更新它的內容。

回答

3

封閉!

$(document).ready(function(){ 
    $(".divClass").each(
     function(e) { 
      $(this).attr('divValue', $('p.pClass1', this).text()); 
      $('p.pClass1', this).text('?'); 

      $(this).click(function(e) { 
       e.preventDefault(); 

       // Store 'this' locally so it can be closed 
       // by the function scope below 
       var self = this; 

       $.ajax({ 
        type: "POST", 
        url: "ajax.php", 
        data: "val=" + $(this).attr('divValue'), 
        success: function(msg) { 
         myData = JSON.parse(msg); 

         // Now used your closed variable here 
         $('p.pClass1', self).html(myData.results[0]); // problem exists here 
        } 
       }); 
      }); 
     } 
    ); 
}); 
+0

這是我錯過了什麼。很簡單,謝謝。 – Michael 2009-11-17 20:56:13

+1

不要忘記在「myData = ...」部分之前添加一個「var」以防止它被聲明爲全局變量。另外,如果您提供帶有「datatype:'json'」參數的$ .ajax()函數,則不必使用JSON.parse來解析結果。 – 2009-11-17 23:39:09

1
var self = this; 
$.ajax({ ..., success: function (msg) { ... $('p.pClass1', self) ... } ... 
相關問題