问题
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. Is it possible to save color to 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:
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 += "<p id='item" + i + "' isPriority='" +
todo.priority.isPriority + "'>" + todo["name"] + '<p>' +
"<button class='remove'>Delete</button>" + " " +
"<button class='priority' value='item" + i + "'>Priority</button>";
};
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/
来源:https://stackoverflow.com/questions/37575999/how-do-i-save-background-color-to-localstorage