gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:00:32 24 4
gpt4 key购买 nike

我正在创建一个带有“添加到收藏夹”按钮的歌本应用程序。我有 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 中。如何实现。

最佳答案

在 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>

关于javascript - 如何将项目添加到本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51303211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com