如何将项目添加到本地存储

新手上路,请多包涵

我正在创建一个带有“添加到收藏夹”按钮的歌本应用程序。我有 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 许可协议

阅读 832
2 个回答

如果您确实需要将数据追加到同一个 LocalStorage 键,则没有内置的追加功能。

但是,您可以使用自定义函数,例如此答案中提出的函数: https ://stackoverflow.com/a/7680123/2446264,并获取以下代码来执行您想要的操作:

 <!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
    localStorage.setItem("list", "<h1>John<h1>");
    appendToStorage("list", "<h2>David<h2>");

    // Retrieve
    document.getElementById("result").innerHTML = localStorage.getItem("list");
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}

function appendToStorage(name, data){
    var old = localStorage.getItem(name);
    if(old === null) old = "";
    localStorage.setItem(name, old + data);
}
</script>

</body>
</html>

原文由 TomasCarvalho 发布,翻译遵循 CC BY-SA 4.0 许可协议

将列表存储在 javascript 数组中。您需要使用不同的键或将多个字符串存储在数组中,然后 JSON.stringify 将其保存在 localStorage 中。类似地,当您从 localStorage 获取相同的字符串然后使用 JSON.parse 将其转换为对象时。

 <!DOCTYPE html>
<html>
<body>

<div id="result"></div>

<script>
// Check browser support
if (typeof(Storage) !== "undefined") {
    // Store
    let list = [];
    list.push("<h1>John<h1>");
    list.push("<h2>David<h2>");
    localStorage.setItem("list", JSON.stringify(list));


    // Retrieve
    document.getElementById("result").innerHTML = JSON.parse(localStorage.getItem("list"));
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
}
</script>

</body>
</html>

原文由 Komal 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题