【发布时间】:2015-09-06 15:58:54
【问题描述】:
Following this fiddle from this question,我写了这段代码:
var currentSlideCount = window.imgIds.length;
for (var i = 11; i < (currentSlideCount + 10); i++) {
// SET UP NEW SLIDE HTML
var newSlide = '<li><img id="apod' + i + '" class="rounded-corners apod-image"></li>';
$('#lightSlider').append(newSlide);
window.imgIds.push('apod'+i);
console.log(window.imgIds);
// GENERATE DATE
var date = new Date();
date.setDate(date.getDate() - i);
var day = date.getDate();
var month = date.getMonth();
var year = date.getFullYear();
console.log(year + "-" + month + "-" + day);
// GENERATE XML REQUEST
function foo(callback) {
var apodUrl = "https://api.nasa.gov/planetary/apod?concept_tags=True&date=" + year + "-" + month + "-" + day;
var apodXml = new XMLHttpRequest();
apodXml.open('GET', apodUrl, true);
apodXml.send(null);
// WHEN REQUEST IS READY
apodXml.onreadystatechange=function() {
if (apodXml.readyState==4 && apodXml.status==200) {
var apodParse = JSON.parse(apodXml.responseText);
callback(apodParse.url)
console.log(apodParse.url);
}
}
}
foo(function(result) {
var newSlideId = 'apod' + i;
document.getElementById(newSlideId).src = result;
});
然而,我仍然在 img 标记上收到 Cannot set property 'src' of null 控制台错误,该错误是在调用其 src 属性很久之前创建的。据我了解,我已经正确设置了回调。为什么这仍然不起作用?
【问题讨论】:
标签: javascript jquery asynchronous scope closures