2011-10-19 19 views
0

爲什麼不會被附加?

$.ajax({ 
       type: 'GET', 
       dataType: 'json', 
       cache: false, 
       url: 'barfoochakalaka', 
       success: 
        function(response) { 
         $.each(response, function(index, val) {        
          $(this).parent().parent().append('foo'); 
         }); 

        } 
}) 
+0

檢查$(this)的值 – sathis

+0

你想'this'是什麼? – Joe

+0

,因爲它之前的行出現錯誤。看看javascript控制檯,看看錯誤信息是什麼。在'$ .each()'中的 – Hogan

回答

4

因爲裏面eachthis被設置爲當前元素上迭代(docs),所以一般我們定義this是我們前,可別的東西NTER的each環:

var that = this; 
$.each(response, function(index, val) { 
    var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>'; 
    $(that).parent().parent().append('foo'); 
}); 

然而,在這個情況thissuccess回調一個AJAX請求的等於其發起請求,而不是DOM元素你後的jqXHR對象,所以我們必須將var that = this更遠離;

var that = this; 
$.ajax({ 
    type: 'GET', 
    dataType: 'json', 
    cache: false, 
    url: 'barfoochakalaka', 
    success: function(response) { 
     $.each(response, function(index, val) { 
      var content = '<div class="link-history">' + val.date + ', ' + val.userid + ', ' + val.status + '</div>'; 
      $(that).parent().parent().append('foo'); 
     }); 

    } 
}) 
0

響應可能不是數組,只是一個字符串。儘量分配給一個元素的響應,然後使用選擇做一個。每()之前,搶在該元素的所有孩子

3
var $this = $('#Selector').parent().parent(); 
$.ajax({ 
       type: 'GET', 
       dataType: 'json', 
       cache: false, 
       url: 'barfoochakalaka', 
       success: 
        function(response) { 
         $.each(response, function(index, val) { 
          var content = '<div class="link-history">'+ val.date + ', ' + val.userid + ', ' + val.status + '</div>'; 
          $this.append('foo'); 
         }); 

        } 
}) 


編輯:

添加.parent().parent()到原來的選擇,所以你每個迴路都不會調用這個

0

你的反應是不元素的對象,這是最有可能的字符串可能與你的選擇列表(?),如果這是它然後使用$($(this))