gpt4 book ai didi

javascript - 为什么我的本地存储不起作用?

转载 作者:行者123 更新时间:2023-12-02 14:31:42 24 4
gpt4 key购买 nike

我尝试使用 localStorage 制作一个简单的待办事项列表,但它不起作用。知道为什么吗?有时,当我离开并返回时,会出现我添加的项目,所以我想知道这是否是我的浏览器(Chrome 和 Safari)上的简单设置。

function get_todos() {
var todos = new Array;
var todos_str = localStorage.getItem('todo');
if (todos_str !== null) {
todos = JSON.parse(todos_str);
}
return todos;
}


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


function remove() {
var id = this.getAttribute('id');
var todos = get_todos();
todos.splice(id, 1);
localStorage.setItem('todo', JSON.stringify(todos));

show();

return false;
}

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

for (var i=0;i<todos.length;i++) {
var todo = todos[i];
console.log(todo);
if (todo.id==id) {
todo.priority.isPriority = true;
todo.priority.color = "red";
}
}

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

show();

return false;
}

function show() {
var todos = get_todos();

var html = '<p>';
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>";
};


document.getElementById('item').innerHTML = html;

var button1 = document.getElementsByClassName('priority');
for (var i=0; i < button1.length; i++) {
button1[i].addEventListener('click', priority);
};

var button2 = document.getElementsByClassName('remove');
for (var i=0; i < button2.length; i++) {
button2[i].addEventListener('click', remove);
};
}


document.getElementById('add').addEventListener('keyup', add);
show();

http://codepen.io/kiddigit/pen/PzZgMQ

最佳答案

您的问题是您绑定(bind)的是 keyup 而不是 click 按钮:

document.getElementById('add').addEventListener('click', add);

您可以考虑将输入和按钮包装在表单中:

<form id="add_form">
<input id="task" type="text">
<button id="add" type="submit">Add</button>
</form>

然后监听所述表单submit事件:

document.getElementById('add_form').addEventListener('submit', function(event) {
event.preventDefault();
add();
});

这样 enter 也将在输入字段中起作用。

关于javascript - 为什么我的本地存储不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37765063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com