【问题标题】:using localStorage to track a checkbox使用 localStorage 跟踪复选框
【发布时间】:2020-01-05 07:24:53
【问题描述】:

得到这个应用程序:

https://jsfiddle.net/Lqoe4awh/

所以我有一个用于项目和 toDos 的 localStorage,项目设置为使用本地存储保存,todos 也是如此,但我在 todos 列表模式中有一个复选框,我不知道如何将它保存在 localStorage 中并检索每次你再次打开同一个项目的模态时它。

tldr:当我打开项目时,我希望复选框在我关闭后仍保持选中状态;

function checkBox() {
    let allCheckBoxes = document.querySelectorAll('.checkbox');
    allCheckBoxes.forEach(function(el){
        el.addEventListener('click', function(e){
                e.target.dataset.check = "checked"
                e.target.parentElement.style.textDecoration = "line-through"
                localStorage.setItem("todo" , JSON.stringify(toDoStorage))

        })
    })
}

【问题讨论】:

  • 我会说,从本地存储中获取任务,取消字符串化,更新所需任务对象的属性“检查”,字符串化,将其放回本地存储。既然您似乎已经实现了其中的大部分,那么究竟是什么问题?
  • 通常最好在此处发布相关代码而不是链接,因为链接可能会失效并且不是每个人都可以关注它们。此外,使用更简洁的框架会更好;)请参阅here

标签: javascript local-storage


【解决方案1】:

我不知道从哪里开始在您的项目中使用它,但这里有一个简单的示例,说明如何通过localStorage 管理复选框的状态。 请注意,localStorage 的实际用途已被注释掉,因为我遇到了 SecurityError。但是我在小提琴中对其进行了测试;)

// get reference to the list
const list = document.getElementById('my-todos');
// simple helper to create a todo-item
const todoItem = ({ title, done }) => `<li>
    <span>${title}</span>
    <input type="checkbox" ${done ? 'checked' : ''}>
  </li>`;
// our tasks. reading from localStorage is commented out because "The operation is insecure"
// const tasks = JSON.parse(localStorage.getItem('todos')) || 
const tasks = [
  {
    title: 'task 1',
    done: false
  },{
    title: 'task 2',
    done: true
  },{
    title: 'task 3',
    done: false
  }  
];

tasks.forEach(t => list.innerHTML += todoItem(t));

// adjust the status of a task when the corresponding checkbox is changed
list.onchange = (({ target }) => {
  tasks
  .find(({title}) => title === target.previousElementSibling.textContent)
  .done = target.checked;
  
  // again, insecure
  // localStorage.setItem('todos', JSON.stringify(tasks));
});
&lt;ul id="my-todos"&gt;&lt;/ul&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多