如何将项目添加到本地存储 [英] How to add item to local storage

查看:78
本文介绍了如何将项目添加到本地存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个带有添加到收藏夹按钮的歌曲书应用程序。我在song1.html中有song1.html song2.html和favorite.html。

I am creating a song book app with 'add to favorite' button. i have song1.html song2.html and favorite.html.

,当点击添加到收藏夹按钮时。我正在本地存储中存储该歌曲的链接。

in song1.html, when add to favorite button is clicked. i am storing the link to that song in local storage.

这是我的song1.html

This is my 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>

。我将第二首歌曲的链接存储在本地存储空间中。

in song2.html, when add to favorite button is clicked. i am storing the link of the second song in local storage.

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将检索我存储在本地存储中的链接。

now i have a favorite.html for listing my favourite songs. and favourite.html will retrieve the links that i stored in local storage.

favorite.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>

现在我要在收藏夹中同时显示歌曲1和歌曲2 html的。
但是只有歌曲2显示在favourite.html中。如何实现这一点。

Now i want to show both song 1 and song 2 in favorite.html. but only song 2 is displayed in favourite.html. How to accomplish this.

推荐答案

如果确实需要将数据附加到同一个LocalStorage密钥,则没有内置附加函数。

If you really need to append data to the same LocalStorage key, there is no built-in append function.

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

However, you can use a custom function, for instance the one proposed in this answer: https://stackoverflow.com/a/7680123/2446264, and get the following code to do what you want:

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

这篇关于如何将项目添加到本地存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆