How do I save background color to localStorage?

后端 未结 1 443
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 00:59

I have a to-do list that saves to localStorage with a Priority button that changes the background color to red. That color doesn\'t save on refresh or adding a new to-do item. I

1条回答
  •  日久生厌
    2021-01-29 01:36

    If you want to store a background color with the item, you're going to need to store the item as an object instead of just the name.

    I recommend adding logic like this to your add method:

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

    Then, when you show() those, your loop will look like this:

      for (var i = 0; i < todos.length; i++) {
          var todo = todos[i];
          html += "

    " + todo["name"] + '

    ' + "" + " " + ""; };

    Then when you set the priority on the object, you're just setting the

    todos[i].priority.isPriority = true;
    

    and

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

    If you want to define your color based on the property, you could just set a property in the html as isPriority=true and then in css do this:

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

    Check out this example: https://jsfiddle.net/1Lgrb7c8/2/

    0 讨论(0)
提交回复
热议问题