2011-04-08 57 views
2

我的AJAX功能並不像我期望的那樣工作。jQuery AJAX成功上下文

AJAX成功回調中的「this」似乎並不是指showSnapshotComment函數範圍內的「this」。

我試過使用上下文它仍然不工作。我的用法可能不正確。我可能會推翻它。

function showSnapshotComments(snapshot) { 
    var self = $j(this); 
    alert($j(this).attr('class')); 
    $j.ajax({ 
    cache: false, 
    context: this, 
    url: 'show_snapshot_comments/' + snapshot.id, 
     async: true, 
    dataType: 'script', 
    success: function() { 
    $j('#snapshots a.photo').each(function(i) { 
     $j(this).qtip({ 
     content: $j(this).nextAll('.info').eq(i), 
     position: { 
      target: 'mouse', 
      adjust: { mouse: true }, 
       viewport: $j(window) 
      }, 
     hide: { 
      event: 'click mouseleave', 
      delay: 300 
     }, 
     show: { 
      solo: true, 
      event: 'click mouseenter' 
     }, 
     style: { 
      tip: true, 
      classes: "ui-tooltip-light" 
     } 
    }); 
}); 

    } 
    }); 
} 

回答

0

的問題是與此變量的作用域。 嘗試下面的代碼來代替:

var self = $j(this);  
var that = this; 
alert($j(this).attr('class'));  
$j.ajax({  
    cache: false,  
    context: that, 
    . 
    . 
    . 
    . 
1

this的AJAX成功回調裏面確實涉及到同一thisshowSnaphotComments答案你得到的是正確的,但最簡單的答案解釋說,真正的問題是$j().each函數內成功回調 - 它會改變上下文,因爲它遍歷DOM元素......但AJAX成功的this是正確的嘗試以下內容:

function showSnapshotComments(snapshot) { 
    var self = $j(this); 
    alert($j(this).attr('class')); 
    $j.ajax({ 
    cache: false, 
    context: this, 
    url: 'show_snapshot_comments/' + snapshot.id, 
    async: true, 
    dataType: 'script', 
    success: function() { 
     var self = this; // same this as in showSnapshotComments 
     $j('#snapshots a.photo').each(function(i) { 
     $j(self).qtip({ // this changed to self 
      content: $j(self).nextAll('.info').eq(i), // same here 
      position: { 
      target: 'mouse', 
      adjust: { mouse: true }, 
      viewport: $j(window) 
      }, 
      hide: { 
      event: 'click mouseleave', 
      delay: 300 
      }, 
      show: { 
      solo: true, 
      event: 'click mouseenter' 
      }, 
      style: { 
      tip: true, 
      classes: "ui-tooltip-light" 
      } 
     }); 
     }); 
}