Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何将项目添加到本地存储_Javascript_Html_Local Storage - Fatal编程技术网

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

Javascript 如何将项目添加到本地存储,javascript,html,local-storage,Javascript,Html,Local Storage,我正在创建一个带有“添加到收藏夹”按钮的歌曲集应用程序。我有song1.html song2.html和favorite.html 在song1.html中,单击“添加到收藏夹”按钮时。我正在本地存储该歌曲的链接 这是我的歌曲1.html 添加到收藏夹 函数mySongOne(){ setItem(“favsong”和“”); } 使用localStorage时,每个键只能有一项localStorage允许您将字符串数据存储为值,因此我们可以使用JSON 您可以序列化要添加的项数组,然后将它

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

在song1.html中,单击“添加到收藏夹”按钮时。我正在本地存储该歌曲的链接

这是我的歌曲1.html


添加到收藏夹
函数mySongOne(){
setItem(“favsong”和“”);
}

使用
localStorage
时,每个键只能有一项
localStorage
允许您将字符串数据存储为值,因此我们可以使用
JSON

您可以序列化要添加的项数组,然后将它们附加到
localStorage
中的键中

参考文献:


. StackOverflow不允许
localStorage
,所以我在那里托管了我的代码

代码:


let items=['John','David','Mary','Bob'];
//将数组字符串化并存储它
setItem(“list”,JSON.stringify(items));
//从localStorage解析字符串化数组
让itemsRetrieved=JSON.parse(localStorage.getItem('list');
//使用.list类获取div
让div=document.querySelector('.list');
//迭代检索到的数组并追加项
itemsRetrieved.forEach(item=>{
div.innerHTML+=项;
});
//添加项目
itemsRetrieved.push('Dylan');
//字符串化新数组并覆盖密钥
setItem(“list”,JSON.stringify(itemsRetrieved));
代码[对于喜欢封装的人]:


let items=['John','David','Mary','Bob'];
//字符串化数组并存储它[初始值]
setItem(“list”,JSON.stringify(items));
//返回解析后的数组
函数getData(键){
返回JSON.parse(localStorage.getItem(key));
}
//返回新数组
函数addData(键,项){
//获取当前数组
让currentData=getData(键);
//添加项目
currentData.push(项目);
//字符串化新数组并覆盖密钥
setItem(key,JSON.stringify(currentData));
返回当前数据;
}
//从localStorage解析字符串化数组
让itemsRetrieved=getData('list');
//使用.list类获取div
让div=document.querySelector('.list');
//添加项目
itemsRetrieved=addData('list','Dylan');
//迭代检索到的数组并追加项
itemsRetrieved.forEach(item=>{
div.innerHTML+=项;
});

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


//检查浏览器支持
if(类型(存储)!=“未定义”){
//贮藏
让列表=[];
列表。推送(“约翰”);
列表。推送(“大卫”);
setItem(“list”,JSON.stringify(list));
//取回
document.getElementById(“结果”).innerHTML=JSON.parse(localStorage.getItem(“列表”));
}否则{
document.getElementById(“结果”).innerHTML=“对不起,您的浏览器不支持Web存储…”;
}

你做错了什么:

localstorage不存储数据类型,而是存储字符串

例如,如果要在localstorage属性中存储整数,则数据类型将始终作为字符串返回

由于您试图存储一个值数组,因此需要创建一个CSV(逗号分隔值)方法

您可以使用以下两种方法之一将其解析到本地存储中

  • JSON(参见下面的示例)
  • 拆分(变量。拆分(“,”)
请务必注意,浏览器设置了在本地存储和会话存储之间分配5MB数据的限制

如果您的编辑的示例中存储了各种URL,则当需要存储大量数据时,这可能会导致问题

您的解决方案的替代方案可能是使用SQL表的唯一ID为歌曲表条目创建喜爱歌曲的CSV

但是,如果您的代码只使用前端语言,如HTML和JAVASCRIPT,那么您可能更喜欢使用IndexedDB

这将允许您创建可脱机访问的本地数据库,并允许您更轻松地调用和编辑值,例如

本地存储示例:

var blLocalStorage=false;
函数funcinitiate(){
if(类型(存储)!=“未定义”){
log(“在此浏览器上检测到本地存储”);
blLocalStorage=true;
}否则{
console.log(“此浏览器不支持本地存储,请更新”);
}
}
funTestLocalStorage()函数{
var strLocalStorage=localStorage.getItem(“FavSongs”);
if(strLocalStorage==null){
返回false;
}否则{
返回true;
}
}
函数funGetSongFavorites(){
if(blLocalStorage){
if(funTestLocalStorage()){
var arrLocalStorage=JSON.parse(localStorage.getItem(“FavSongs”);
var elOutput=document.querySelector(“结果”);
对于(i=0;i”+arrLocalStorage[i]
}
}
}否则{
log(“无本地存储-函数FungetSongFavorites中止”);
}
}
函数funAddFav(strURL){
if(blLocalStorage){
var strLocalStorage=localStorage.getItem(strURL);
if(strLocalStorage==null){
setItem(“FavSongs”,strURL);
}否则{
var arrList=JSON.parse(localStorage.getItem('FavSongs');
arrList.push(strURL);
}
setItem('FavSong',JSON.stringify(arrList));
log(“收藏夹列表更新:+strURL”);
}否则{
log(“无本地存储-函数funAddFav中止”);
}
}
document.addEventListener(“DOMContentLoaded”,funInitiate,false);
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>']; // Stringify the array and store it localStorage.setItem("list", JSON.stringify(items)); // Parse the stringified array back from localStorage let itemsRetrieved = JSON.parse(localStorage.getItem('list')); // Get div with .list class let div = document.querySelector('.list'); // Iterate retrieved array and append items itemsRetrieved.forEach(item => { div.innerHTML += item; }); // Add an item itemsRetrieved.push('<span style="color: red;">Dylan</span>'); // Stringify the new array and overwrite the key localStorage.setItem("list", JSON.stringify(itemsRetrieved));
let items = ['<h1>John<h1>', '<h2>David<h2>', '<h3>Mary<h3>', '<h4>Bob<h4>'];

// Stringify the array and store it [Initial]
localStorage.setItem("list", JSON.stringify(items));

// Returns parsed array
function getData(key) {
    return JSON.parse(localStorage.getItem(key));
}

// Returns new array
function addData(key, item) {
    // Get current array
    let currentData = getData(key);

    // Add an item
    currentData.push(item);

    // Stringify the new array and overwrite the key
    localStorage.setItem(key, JSON.stringify(currentData));

    return currentData;
}

// Parse the stringified array back from localStorage
let itemsRetrieved = getData('list');

// Get div with .list class
let div = document.querySelector('.list');

// Add an item
itemsRetrieved = addData('list', '<span style="color: red;">Dylan</span>');

// Iterate retrieved array and append items
itemsRetrieved.forEach(item => {
    div.innerHTML += item;
});
var strLocalStorage = "John, Peter, Fred, Paul, Mary, Elizabeth";
var initialValue = ['<h1>John<h1>']; // array of strings
// since Local Storage accepts only string values, 
// you can store an array or any other object by using JSON.stringify function
localStorage.setItem('list', JSON.stringify(initialValue);

// updating local storage
var list = JSON.parse(localStorage.getItem('list');
list.push('<h2>David<h2>');
localStorage.setItem('list', JSON.stringify(list));
var output = '';
for (var i = 0; i < list.length; i++) {
  output = output + list[i];
}

document.getElementById("result").innerHTML = output;