UPDATE
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:
- Set
img
to nice.jpg
- Call
$.post
- Call
alert
- Set
img
to newname.jpg
Original answer:
If the code you are using exists exactly as you posted it, then:
img
is already available inside your anonymous callback function.
- Yes, you can change the value of
img
from inside the function as well.
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:
WORKS
function getPost(){
var img = "nice.jpg";
$.post('/path', {key:value}, function(data){
alert(img); // alerts "nice.jpg"
});
}
DOES NOT WORK
function changeImage(){
var img = "nice.jpg";
getPost();
}
function getPost(){
$.post('/path', {key:value}, function(data){
alert(img); // img is undefined
});
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…