我正在尝试使用 jQuery getJSON()
函数中的匿名函数来填充 JavaScript 中的数组,如下所示。
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
var links = [];
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
});
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
但是,当我执行 for 循环时,链接数组显示为空。这是怎么回事?
最佳答案
尝试一下:
$(document).ready(function() {
function Link(url, title) {
this.url = url;
this.title = title;
}
$.getJSON("http://reddit.com/r/programming/.json?jsonp=?", function(data) {
var links = [];
$.each(data.data.children, function(i, item) {
var title = item.data.title;
var url = item.data.url;
links.push(new Link(url, title));
})
for(var i=0; i< links.length; i++) {
var output = "<a href='" + k + "'>" + links[k] + "</a>";
$('<p>' + link + '</p>').appendTo('#content');
}
});
});
您的循环可能在回调之前执行;)
关于javascript - 匿名函数中的变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10891203/