我有一个待办事项列表,它通过一个优先级按钮保存到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;
}
如果要
将背景颜色与项目一起存储,则需要将项目存储为对象,而不仅仅是名称。
我建议将这样的逻辑添加到您的 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/