【问题标题】:Add and remove to Local Storage添加和删​​除到本地存储
【发布时间】:2020-06-05 14:48:25
【问题描述】:

我正在创建一个带有添加到收藏链接的列表。 我想使用纯 JS 将 'foo' 值存储在本地存储中。然后,一旦我再次单击,它就会被删除。 也许我无法将标识符绑定到样式名称。 我想重复这里的方式https://jsfiddle.net/farhadB/ocgcejg2/,但我不能。

document.addEventListener('click', function(e) {
  if (e.target && e.target.classList.contains('photo')) {
    e.target.classList = "foo";
  } else if (e.target && e.target.classList.contains('foo')) {
    e.target.classList = "photo";
  }
});

【问题讨论】:

  • classList 是一个类列表,您正在尝试为其分配一个字符串...这不可能,现在可以吗?

标签: javascript local-storage


【解决方案1】:

我认为主要问题是,您正在设置classListclassListreadonly attribut,您可以使用 add 方法添加类。

也许你的意思是:

e.target.classList = "photo";

这个:

e.target.className = "photo";

e.target.classList.add("photo");

【讨论】:

  • 谢谢,但如果我使用添加和删除,我就无法改回类。 codepen.io/insomikk/pen/vYNPJoY - 完整代码
  • 在 codepen 中它不起作用,因为您没有设置任何带有类的列表项。因此,点击事件不会真正做任何事情。当您将类 photo 添加到所有列表项时,它会正常工作。只是样式问题。
【解决方案2】:

您需要多个链接

let store;   
document.addEventListener('click', function(e) {
  const tgt = e.target;
  const photo = tgt.classList.contains('photo');
  const foo   = tgt.classList.contains('foo');
  if (foo || photo) {
    tgt.classList.toggle("foo",photo);
    tgt.classList.toggle("photo",foo);
    store = [...document.querySelectorAll(".foo").map(ele => ele.id)
    localStorage.setItem('store',JSON.stringify(store));
  }
});
window.addEventListener("load",function() {
  store = JSON.parse(localStorage.getItem('store')) || [];
  store.forEach(id => {
    const ele = document.getElementById(id);
    ele.classList.add("foo");
    ele.classList.remove("photo");
  });
})

【讨论】:

    【解决方案3】:

    希望对你有帮助

    document.addEventListener('click', function(e) {
      if (e.target && e.target.classList.contains('photo')) {
        e.target.classList.add("foo");
        e.target.classList.remove("photo");
        localStoarge.favlink = <link name here>;
      } else if (e.target && e.target.classList.contains('foo')) {
        e.target.classList.add("photo");
        e.target.classList.remove("foo");
        localStoarge.favlink = null; // Delete fav link
      }
    });
    

    【讨论】:

    • if(e.target.classList.contains('...')) 是多余的——你已经确定了——你也有错别字
    猜你喜欢
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    相关资源
    最近更新 更多