首页 > 解决方案 > 将项目添加到收藏夹并将其保存在 Cookie 中

问题描述

我有这个项目:

<li><a style="display: none">Movie</a><div id="movie-item" class="filterDiv thriller science-fiction action horror war 2018"></div></li>

还有一个按钮,可让您将该项目保存在收藏夹中:

<button onclick="document.getElementById('movie-item').item.classList.add('favorites');">Mark as favorite</button>

这很完美,因为当我点击“收藏夹”部分时,该项目会正确显示!但问题是:我想创建一个 Cookie 来保存该项目被标记为收藏。

示例:https ://codepen.io/anon/pen/GzOmNe#anon-login

有人可以帮助我吗?谢谢

标签: javascripthtmlcookiessave

解决方案


我不建议使用 cookie。您应该改用 localStorage。

function saveFav () {

  document.getElementById('movie-item').classList.add('favorites');
  
  // Save
  localStorage.setItem('favorites', 'movie');
  // Get
  var fav = localStorage.getItem('favorites');
  console.log(fav);
}
<li><a style="display: none">Movie</a><div id="movie-item" class="filterDiv thriller science-fiction action horror war 2018"></div></li>

<button onclick="saveFav()">Mark as favorite</button>


推荐阅读