因爲裏面each
,this
被設置爲當前元素上迭代(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');
});
然而,在這個情況,this
在success
回調一個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');
});
}
})
檢查$(this)的值 – sathis
你想'this'是什麼? – Joe
,因爲它之前的行出現錯誤。看看javascript控制檯,看看錯誤信息是什麼。在'$ .each()'中的 – Hogan