Javascript 通过带有变量的 src 设置图像的问题

Problem with Javasript setting an image via src with a variable

我正在尝试将图像设置为带有 src 的 html 元素。该图像是我从 spotify 获得 link 的 spotify 专辑封面(link 看起来像这样:https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828

这是我的代码:

const getSongData = () => {
    currentlyPlaying= localStorage.getItem("currentlyPlaying");
    songDuration = localStorage.getItem("songDuration");
    currentAlbum = localStorage.getItem("currentAlbum");
    currentArtist = localStorage.getItem("currentArtist");
    currentAlbumCover = localStorage.getItem("currentAlbumCover");

    document.getElementById('currentlyPlaying').innerHTML = currentlyPlaying;
    document.getElementById('songDuration').innerHTML = (`${(songDuration/1000)/60}:${(songDuration/1000)%60}`);
    document.getElementById('currentAlbum').innerHTML = currentAlbum;
    document.getElementById('currentArtist').innerHTML = currentArtist;
    document.getElementById('currentAlbumCover').src = currentAlbumCover;
    //console.log(currentAlbumCover);
}

所以变量 currentAlbumCover 包含 link 并且这不起作用 我收到此错误消息:

有趣的是,如果我像这样直接将 link 放入,它就可以正常工作:

document.getElementById('currentAlbumCover').src = 'https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828';

您收到的错误显示 404 未找到。

这是因为 http://localhost:5500 被添加到您想要的 link 之前。

你最终得到 http://localhost:5500/https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828

当你只想https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828

我怀疑 localStorage.getItem("currentAlbumCover") 正在返回连接值,因此可能值得检查一下您是如何将值保存到 localStorage 的。

尝试在控制台中转储您的变量,看起来您有一个绝对 URL 被用作相对路径。

如果我的想法是正确的,这将转储: /https://i.scdn.co/image/ab67616d00001e02015c484a7aca592df1a77828

所以currentAlbumCover前面可能会有'/'。

希望对您有所帮助!

我发现错误了! 我从 Spotify 开始并以引号结尾的字符串,我没有注意到在控制台中...... 此行修复它:

currentAlbumCover = localStorage.getItem("currentAlbumCover").replace(/\"/g, '');