2010-03-29 118 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