joh*_*ton 1 html javascript local-storage
我正在使用"添加到收藏夹"按钮创建一个歌曲书应用程序.我有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>
Run Code Online (Sandbox Code Playgroud)
在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>
Run Code Online (Sandbox Code Playgroud)
现在我有一个favorite.html用于列出我最喜欢的歌曲.和favourite.html将检索我存储在本地存储中的链接.
favorite.html
<!DOCTYPE html>
<html>
<body onload="myFunction()">
<div id="result"></div>
<script>
function myFunction() {
document.getElementById("result").innerHTML = localStorage.getItem("favsong");
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在我想在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>
Run Code Online (Sandbox Code Playgroud)