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

时间:2018-07-12 10:25:43

标签: javascript html 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>

单击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>

现在我有一个favourite.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>

现在,我想在favorite.html中同时显示歌曲1和歌曲2。 但favourite.html中仅显示歌曲2。如何做到这一点。

5 个答案:

答案 0 :(得分:5)

将列表存储在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>

答案 1 :(得分:3)

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

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

参考:


JSFiddle。 StackOverflow不允许localStorage,所以我在这里托管了代码。

代码:


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;
});

答案 2 :(得分:2)

基本上,您需要将这些数据存储为字符串列表(或使用其他键“ list1”,“ list2”等...)。

因此,当您最初将价值投入本地存储时,您需要执行以下操作:

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;

答案 3 :(得分:1)

您在做什么错了:

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

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

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

var strLocalStorage = "John, Peter, Fred, Paul, Mary, Elizabeth";

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

  • JSON(请参见下面的示例)
  • SPLIT(variable.split(“,”);

请务必注意,浏览器将LocalStorage和SessionStorage之间分配的数据限制为5MB。

在需要存储大量数据的情况下,这可能会引起问题,例如在您进行编辑的示例中,存储了各种URL

替代您的解决方案的方法是,使用SQL Table的唯一ID为歌曲表条目创建收藏歌曲的CSV。

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

How to use Indexed DBs

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

LocalStorage示例:

var blLocalStorage = false;

function funInitiate(){
  if (typeof(Storage) !== "undefined") {
    console.log("localstorage detected on this browser");
    blLocalStorage = true;
  }else{
    console.log("local storage is not supported by this browser, please update");
  }
}

function funTestLocalStorage(){
  var strLocalStorage = localStorage.getItem("FavSongs");
  if(strLocalStorage === null){
    return false;
  }else{
    return true;
  }
}

function funGetSongFavorites(){
  if(blLocalStorage){
    if (funTestLocalStorage()){
      var arrLocalStorage = JSON.parse(localStorage.getItem("FavSongs"));
      var elOutput = document.querySelector("#result");
      for(i = 0; i < arrLocalStorage.length; i++){
        elOutput.innerHTML += "<br>" + arrLocalStorage[i]
      }
    }
  }else{
    console.log("No local storage - function funGetSongFavourites aborted");
  }
}

function funAddFav(strURL){
  if(blLocalStorage){
    var strLocalStorage = localStorage.getItem(strURL);
    if(strLocalStorage === null){
      localStorage.setItem("FavSongs", strURL);
    }else{
      var arrList = JSON.parse(localStorage.getItem('FavSongs'));
      arrList.push(strURL);
    }
    localStorage.setItem('FavSong', JSON.stringify(arrList));
    console.log("Favourite Lists update: " + strURL);
  }else{
    console.log("No local storage - Function funAddFav aborted");
  }
}

document.addEventListener("DOMContentLoaded", funInitiate, false);
<!DOCTYPE html>
<html>
    <head>
      <title>Webpage Title</title>
      <script src="pathToJSScriptShownBeneath"></script>
    </head>
    <body>
        <button onclick="funAddFav('http://youtube.com')">
           Add to favorite
        </button>
        <div id="result"></div>
    </body>
</html>

索引数据库示例

 var songList = [
  { id: 1, artist: "2pac", title: "Dear Mama", URL: "https://www.youtube.com/watch?v=Mb1ZvUDvLDY" },
  { id: 2, artist: "Biggie Smalls", title: "Hypnotize", URL: "https://www.youtube.com/watch?v=glEiPXAYE-U" }
];

const dbName = "favSongs";
var request = indexedDB.open(dbName, songList.length);

request.onerror = function(event) {
  console.log("An Error has occured, script will now exist";
  return;
};

request.onupgradeneeded = function(event) {
  var db = event.target.result;
  var objectStore = db.createObjectStore("SongList", { keyPath: "id" });
  // There can be multiple songs by 1 artist or band therefore this will
  // declare this as a false unique entry, the sample applies for song titles
  // some songs have the same title but performed by different artists.
  objectStore.createIndex("artist", "artist", { unique: false });
  
  objectStore.createIndex("title", "title", { unique: false });
  // Song URLs will be unique, so we set this as a individually unique
  objectStore.createIndex("URL", "URL", { unique: true });

  // Use transaction oncomplete to make sure the objectStore creation is 
  // finished before adding data into it.
  objectStore.transaction.oncomplete = function(event) {
    // Store values in the newly created objectStore.
    var customerObjectStore = db.transaction("favSongs", "readwrite").objectStore("SongList");
    customerData.forEach(function(songList) {
      customerObjectStore.add(songList);
    });
  };
};

// Retrieving Data:
var transaction = db.transaction(["favSongs"]);
var objectStore = transaction.objectStore("SongList");
var request = objectStore.get(2);
request.onerror = function(event) {
  console.log("Entry doesnt exist of has been deleted");
};

request.onsuccess = function(event) {
  var strArtist = request.result.artist;
  var strTitle = request.result.title;
  var strURL = request.result.URL;
};

// Deleting Data
var request = db.transaction(["favSongs"], "readwrite")
                .objectStore("SongList")
                .delete(1);
  request.onsuccess = function(event) {
    console.log ("Entry 1 has been deleted");
  };

答案 4 :(得分:1)

如果您确实需要将数据附加到相同的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>