用户输入一些任务并单击“添加按钮”后,我希望将新项目保存在本地存储中。 这是下面的代码: http://jsfiddle.net/ovesyan19/mcm36/1/
HTML
<form class="new_item">
<input type="text" class="text_field" name="server_input" id="text_field" placeholder="Write a new task here..." onfocus="this.placeholder = ''" onblur="this.placeholder = 'Write a new task here...'" />
<input type="submit" class="add_btn" value="Add" />
</form>
<div class="items">
<ul id="tasks_list" class="sortable">
</ul>
</div>
JS
var myTasks = localStorage.getItem("tasks");
if(myTasks===undefined || myTasks===null)
{
myTasks = [];
}
myTasks.push(task);
localStorage.setItem("tasks", myTasks);
答案 0 :(得分:1)
此:
var myTasks = localStorage.getItem("tasks");
if(myTasks===undefined || myTasks===null)
{
myTasks = [];
}
myTasks.push(task);
localStorage.setItem("tasks", myTasks);
应该是:
var myTasks = localStorage.getItem("tasks") || []
if(myTasks != [])
myTasks = JSON.parse(myTasks);
myTasks.push(task);
localStorage.setItem("tasks", JSON.stringify(myTasks));
localStorage
仅包含字符串。因此,您必须使用JSON.stringify
将数组转换为JSON,然后您可以通过JSON.parse('json')