我正在创建一个带有“添加到收藏夹”按钮的歌本应用程序。我有 song1.html song2.html 和 favorite.html。
在 song1.html 中,单击“添加到收藏夹”按钮时。我正在将指向该歌曲的链接存储在本地存储中。
这是我的 song1.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongOne()">add to favorite</button>
<script>
function mySongOne() {
localStorage.setItem("favsong", "<a href='https://www.song1.com'><h1>song1</h1></a>");
}
</script>
</body>
</html>
在 song2.html 中,单击添加到收藏夹按钮时。我正在将第二首歌曲的链接存储在本地存储中。
song2.html
<!DOCTYPE html>
<html>
<body>
<button onclick="mySongTwo()">add to favorite</button>
<script>
function mySongTwo() {
localStorage.setItem("favsong", "<a href='https://song2.com'><h1>song2</h1></a>");
}
</script>
</body>
</html>
现在我有一个 favorite.html 用于列出我最喜欢的歌曲。 favourite.html 将检索我存储在本地存储中的链接。
最喜欢的.html
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<div id="result"></div>
<script>
function myFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>
现在我想在 favorite.html 中同时显示歌曲 1 和歌曲 2。但只有歌曲 2 显示在 favourite.html 中。如何做到这一点。
原文由 john livingston 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果您确实需要将数据追加到同一个 LocalStorage 键,则没有内置的追加功能。
但是,您可以使用自定义函数,例如此答案中提出的函数: https ://stackoverflow.com/a/7680123/2446264,并获取以下代码来执行您想要的操作: