I want to give out the value (defined in function getInfo) of the global var "title" but all i get at the alert(title) is "undefined". Sure i can put the alert in the last function but why i doesnt work this way?
我想给出全局变量“title”的值(在函数getInfo中定义),但是我得到的警报(标题)是“未定义”。当然,我可以把警报放在最后一个功能,但为什么我不这样做?
//[...]
var title;//global var
$(document).ready(
function(){
$.getJSON(url, displayImages)//open func displayImages
});
function displayImages(data) {
$.each(data.photoset.photo, function(i,item){
$.getJSON(url+item.id+"&format=json&jsoncallback=?", getInfo);//open func getInfo
alert(title);//output: undefined
});
}
function getInfo(data2){
title = data2.photo.title._content;//get value of title from json
}
1 个解决方案
#1
1
$.getJSON
is asynchronous, which means that if you put an alert in the getInfo
method, it would fire after the alert(title)
even though it is a line before it.
$ .getJSON是异步的,这意味着如果你在getInfo方法中放置一个警报,它将在警报(标题)之后触发,即使它是它之前的一行。
You could fix this as such:
你可以解决这个问题:
$.getJSON(url+item.id+"&format=json&jsoncallback=?", function(data) {
getInfo(data);
alert(title);
});
#1
1
$.getJSON
is asynchronous, which means that if you put an alert in the getInfo
method, it would fire after the alert(title)
even though it is a line before it.
$ .getJSON是异步的,这意味着如果你在getInfo方法中放置一个警报,它将在警报(标题)之后触发,即使它是它之前的一行。
You could fix this as such:
你可以解决这个问题:
$.getJSON(url+item.id+"&format=json&jsoncallback=?", function(data) {
getInfo(data);
alert(title);
});