存储在待办事项列表中

时间:2014-05-03 12:32:53

标签: jquery html css

用户输入一些任务并单击“添加按钮”后,我希望将新项目保存在本地存储中。 这是下面的代码: 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);

1 个答案:

答案 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')

解析相同的数组