我认为很简单,但我在某处遗漏了一些东西。我正在更改在 HTML 中分配的图像,如下所示:
<a href="properties-single.html" class="img" id="albumPhoto1" style="background-image: url(images/work-1.jpg);"></a>
使用以下代码片段从 JavaScript 中的链接到图像:
var x = 0
var ids = ['albumPhoto1', 'songName1', 'artistName1',
'albumPhoto2', 'songName2', 'artistName2',
'albumPhoto3', 'songName3', 'artistName3'];
data.tracks.items.map((data) => {
console.log(data);
console.log(data.album.images[0].url)
document.getElementById(ids[x]).style.backgroundImage = "url(data.album.images[0].url)";
document.getElementById(ids[x + 1]).innerHTML = data.name;
document.getElementById(ids[x + 2]).innerHTML = data.artists[0].name;
x += 3;
}
这个片段类似于一个循环,遍历有关歌曲的数据数组。我的问题似乎是
document.getElementById(ids[x]).style.backgroundImage = "url(data.album.images[0].url)";
但我不知道在哪里。我可以对上面的 console.log 在控制台中提供的链接进行硬编码,并按预期工作,但它什么也没有显示。
最佳答案
使用反引号 (`) 而不是双引号 (") 应该可以。
document.getElementById(ids[x]).style.backgroundImage =`url(${data.album.images[0].url})`;
关于javascript/HTML 使用 url() 更改图像;未按预期工作(简单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60141546/