如何将背景颜色保存到localStorage?

时间:2016-06-01 18:15:32

标签: javascript local-storage

我有一个待办事项列表,可以使用优先级按钮保存到localStorage,该按钮可将背景颜色更改为红色。该颜色在刷新或添加新的待办事项时不会节省。是否可以将颜色保存到localStorage? https://jsfiddle.net/kiddigit/hg6w01zn/

function priority() {
  var id = this.getAttribute('value');
  var todos = get_todos();

  localStorage.setItem('todo', JSON.stringify(todos));
  document.getElementById(id).style.background = "red";

  return false;
}

1 个答案:

答案 0 :(得分:0)

如果要存储项目的背景颜色,则需要将项目存储为对象而不仅仅是名称。

我建议在add方法中添加这样的逻辑:

function add() {
    var task = document.getElementById('task').value;
    var todos = get_todos();
    var newTask = {
                name:task, 
                id: "item" + todos.length, 
                priority: {
                            isPriority:false, 
                            color:""
                          }
             };

    todos.push(newTask);
    localStorage.setItem('todo', JSON.stringify(todos));

    show();

    return false;
}

然后,当你展示()那些时,你的循环将如下所示:

  for (var i = 0; i < todos.length; i++) {
      var todo = todos[i];
      html += "<p id='item" + i + "' isPriority='" + 
      todo.priority.isPriority + "'>" + todo["name"] + '<p>' + 
      "<button class='remove'>Delete</button>" + " " + 
      "<button class='priority' value='item" + i + "'>Priority</button>";
  };

然后,当您在对象上设置优先级时,您只需设置

todos[i].priority.isPriority = true;

todos[i].priority.color = "red";

如果你想根据属性定义你的颜色,你可以在html中设置一个属性为isPriority = true,然后在css中设置:

[isPriority="true"] {
    background-color: red;
}

查看此示例:https://jsfiddle.net/1Lgrb7c8/2/