gpt4 book ai didi

javascript - jQuery,无法存储 $.get 函数返回的数据

转载 作者:行者123 更新时间:2023-11-29 20:23:31 26 4
gpt4 key购买 nike

我正在尝试将 div#sidebar 变成我应用中的侧边栏。我的代码如下所示。

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

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

它没有用,因为我发现 this(在 $.get 函数内) 这里是 get 请求的上下文,而不是 $('#sidebar')。然后我尝试了类似下面的方法。

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

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

最佳答案

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

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

由于 this 随每个上下文而变化,因此这是一种经常使用的技术,可以在您方便的时候尽早将 this 存储在另一个变量中以捕获正确的上下文。

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

关于javascript - jQuery,无法存储 $.get 函数返回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2536636/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com