在jQuery.post中,如何获取函数外部变量的值? [英] In jQuery.post, how do I get value of variable outside function?
本文介绍了在jQuery.post中,如何获取函数外部变量的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我具有以下功能:
var id = "10";
var type = "Type A";
var img = "myimage.jpg";
jQuery.post("my/path/somefile.php", { instance: 'getUrl', ID : id, type: type},
function(data)
{
jQuery('#logo').attr("src",data.url + img);
},"json");
- 在函数内部时如何获取
img
的值? - 如何在函数内部设置
img = new value
?
- How can I get the value of
img
when I'm inside the function? - How can I sett
img = new value
from inside the function?
更新
此代码未给变量赋予新值:
This code does NOT give a new value to the variable:
logoUrl = "noLogo.png";
jQuery.post("my/path/somefile.php", { instance: 'getUrl', ownerID : "123", type: "brand"},
function(logo)
{
logoUrl = logo.url + "logo/";
},"json");
alert(logoUrl); // This outputs noLogo.png"
推荐答案
更新
在使用回调函数时,重要的是要注意执行流程:
When working with callback functions, its important to pay attention to execution flow:
var img = "nice.jpg";
$.post('/path', { key: value }, function(data){
img = "newname.jpg";
});
alert(img); // Alerts "nice.jpg"
这是因为在回调(而不是在回调函数中)之后发生的所有代码都将首先执行:
It is because any code occurring after the callback (but not in the callback function) is executed first:
- 将
img
设置为nice.jpg
- 致电
$.post
- 致电
alert
- 将
img
设置为newname.jpg
- Set
img
tonice.jpg
- Call
$.post
- Call
alert
- Set
img
tonewname.jpg
原始答案:
如果您使用的代码与您发布的代码完全相同,则:
If the code you are using exists exactly as you posted it, then:
-
img
在匿名回调函数中已经可用. - 是的,您也可以在函数内部更改
img
的值.
img
is already available inside your anonymous callback function.- Yes, you can change the value of
img
from inside the function as well.
使用var
关键字声明变量时,该变量是其当前范围的私有变量,但可用于其范围内的任何其他上下文:
When you declare variable with the var
keyword, it is private to its current scope, but is available to any other contexts contained within its scope:
作品
function getPost(){
var img = "nice.jpg";
$.post('/path', {key:value}, function(data){
alert(img); // alerts "nice.jpg"
});
}
不起作用
function changeImage(){
var img = "nice.jpg";
getPost();
}
function getPost(){
$.post('/path', {key:value}, function(data){
alert(img); // img is undefined
});
}
这篇关于在jQuery.post中,如何获取函数外部变量的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文