我正在尝试将其源设置为下载URL来创建映像,该映像由.getDownloadURL()函数从firebase中检索到。我还想将图像的ID设置为Firebase存储路径,以便获取图像的名称。但是问题是,当我尝试在.getDownloadURL()函数中创建路径时,它说“无法获取未定义的位置”,因为path变量的作用域没有到达内部。我尝试的解决方案是在进入.getDownloadUrl()函数之前创建图像并添加ID,但是由于img是未定义的,所以我无法设置img的.src。无论如何,我将不胜感激,感谢您的宝贵时间。这是我的代码:
for(n=0; n<subarray.length; n++){
//add image with url src
var path = subarray[n].location.path_; //I want the img ID to be this
var img = document.createElement("IMG"); //this is the IMG
img.id = path;
storage.ref(subarray[n].location.path_).getDownloadURL().then(function(url, img){
img.src = url; //error says cannot set .src of undefined
column = "column" + columnNr //columnNr is defined earlier as 1
columnNr = columnNr + 1;
if(columnNr > 4){
columnNr = 1;
}
document.getElementById(column).appendChild(img);
});
}
由于您在img
方法中添加了无效的undefined
参数,因此您正在用img
覆盖变量then()
只需将其删除,如下所示:
for(n=0; n<subarray.length; n++){
//add image with url src
var path = subarray[n].location.path_; //I want the img ID to be this
var img = document.createElement("IMG"); //this is the IMG
img.id = path;
storage.ref(subarray[n].location.path_).getDownloadURL().then(function(url){
img.src = url; //error says cannot set .src of undefined
column = "column" + columnNr //columnNr is defined earlier as 1
columnNr = columnNr + 1;
if(columnNr > 4){
columnNr = 1;
}
document.getElementById(column).appendChild(img);
});
}