2010-03-29 59 views
2

我試圖將div#sidebar轉換爲我的應用中的側欄。我的代碼看起來像下面的代碼。

$('#sidebar').userProfile(); 

jQuery.fn.userProfile = function() { 
    $.get('/users/profile', function(data){ $(this).html(data); }); 
}; 

它沒有工作,因爲我發現($的功能。獲得內部)此背景下,以GET請求,而不是$('#側邊欄)。然後我嘗試了下面的東西。

$('#sidebar').userProfile(); 

#This doesnot work 
jQuery.fn.userProfile = function() { 
    var side_bar = null; 
    $.get('/users/profile', function(data){ side_bar = data; }); 
    $(this).html(side_bar); 
    console.log(side_bar); 
}; 

這也不管用。在firebug控制檯中,當我聲明變量時,我看到了我在上面設置的Null。通過對選擇器進行硬編碼,我通過將代碼更改爲類似下面的代碼來實現它的工作。

#This works, but I cannot turn any element to a sidebar which is sick. 
jQuery.fn.userProfile = function() { 
    $.get('/users/profile', function(data){ $('#sidebar').html(data); }); 
}; 

但是,這不是我想要的,因爲我想將任何元素轉換爲側邊欄。我在哪裏錯了,或者哪個是正確的做法?

回答

3
$('#sidebar').userProfile(); 

jQuery.fn.userProfile = function() { 
    var elem = this; 
    $.get('/users/profile', function(data){ 
    $(elem).html(data); 
    }); 
}; 

由於this變化與每個上下文,這是一個經常使用的技術存儲在另一個變量this在您方便的捕捉到正確的上下文。

你的第二個例子不起作用,因爲.get回調是在以後未定義的時候(當數據回來的時候)異步執行的。

+0

感謝隊友,它的工作。 – Deepak 2010-03-29 09:24:00