代码之家  ›  专栏  ›  技术社区  ›  Deepak

jquery,无法存储$.get函数返回的数据

  •  2
  • Deepak  · 技术社区  · 14 年前

    我想转身 DIV-侧边栏 在我的应用程序的侧边栏中。我的代码如下所示。

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

    它不起作用,因为,我发现 (在$.get函数中) 这里是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控制台中,当我声明变量时,我看到在上面设置的空值,至少我通过硬编码选择器将代码更改为下面这样的值,使其工作。

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

    但这不是我想要的,因为我想把任何元素变成侧边栏。我哪里做错了,或者哪种方法是正确的?

    1 回复  |  直到 14 年前
        1
  •  3
  •   deceze    14 年前
    $('#sidebar').userProfile();
    
    jQuery.fn.userProfile = function() {
      var elem = this;
      $.get('/users/profile', function(data){
        $(elem).html(data);
      });
    };
    

    自从 this 随着每个上下文的变化,这是一种常用的存储技术 在另一个变量中尽早捕获正确的上下文。

    你的第二个例子不起作用,因为 .get 回调在稍后未定义的时间(当数据返回时)异步执行。