开发者

jQuery, unable to store data returned by $.get function

开发者 https://www.devze.com 2022-12-24 06:12 出处:网络
I am trying to turn div#sidebar into a sidebar in my app. My code looks like the 开发者_如何学JAVAone below.

I am trying to turn div#sidebar into a sidebar in my app. My code looks like the 开发者_如何学JAVAone below.

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

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

It didnt work because, I found the this (inside the $.get function) here contexts to the get request and not $('#sidebar'). Then I tried something like below.

$('#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);
};

This doesnt work either. In firebug console I see Null which I am setting on top when I am declaring the variable.Atlast I made it work by changing my code to something like below by hardcoding the selector.

#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); });
}; 

But this is not I wanted because I wanted to turn any element to a sidebar. Where am I goin wrong or which is the correct way of doing it?


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

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

Since this changes with each context, it's an often used technique to store this in another variable at your earliest convenience to capture the right context.

Your second example doesn't work because the .get callback is executed asynchronously at an undefined later time (when the data comes back).

0

精彩评论

暂无评论...
验证码 换一张
取 消