如何保存到localstorage

时间:2015-11-16 21:04:25

标签: javascript jquery html html5

我正在做一个将信息保存到locastorage的简单表单,它将信息保存一次,如果再次尝试,它将保存信息但替换旧信息。有没有办法继续将信息添加到locastorag而不替换旧信息。

HTML:

 <h2>Entry</h2>
        <hr><br>
        <form>
          <label for="title">Title:<br></label><input type="text" name="title" id="title"><br><br>
          <label for="comments">Comments:<br></label><textarea cols="40" rows="4" id="comments"></textarea><br> 
          <button type="reset" class="button-class" id="add">Submit</button> <br><br>
          <a onClick="clearStorage()" style="cursor:pointer"> --> Clear Local Storage <-- </a>
        </form> 
        <div class="entry">

        </div>

JS:

$(document).ready(function()
{
    $('#add').click(function(e)
    {
        e.preventDefault();
        var addText = $('input[name=title]').val();
        var addComment = $('textarea#comments').val();
        $('.entry').append($('<div class="in-ent"><br><h3>Title:</h3><p> ' + addText + '</p><br><h3>Comments:</h3><p> ' + addComment + '<br></p><br></div>'));
        document.getElementById("title").value = "";
        document.getElementById('comments').value = "";

        save(addText,addComment );
    });
}); 

function save(addText,addComment )
{
    var addText =addText;
    var addComment = addComment;
    var myArrayObject = [];
    var entry = new Object();
    entry.title = addText;
    entry.comments = addComment; 
    myArrayObject.push(entry ); 
    localStorage.setItem("Entry", JSON.stringify(myArrayObject));
} 

function clearStorage() {
    console.log("Clearing local storage."); 
    localStorage.clear();
    window.location.href = "index.html";
}

演示:https://jsfiddle.net/jqj82wks/4/

2 个答案:

答案 0 :(得分:1)

无需使用set方法,只需使用:

localStorage.lastname = "Smith";

OR

localStorage["lastname"] = "Smith"

<强> html5 webstorage

答案 1 :(得分:0)

您必须存储数组而不是简单变量:

var addText =addText;
var addComment = addComment;
var myArrayObject = [];
var entry = new Object();
entry.title = addText;
entry.comments = addComment; 
myArrayObject.push(entry ); 

//First entry when localStorage not exist
if ( localStorage.getItem("Entry") == null )
{
    localStorage.setItem("Entry", JSON.stringify(myArrayObject) );
}else{
    //get array stored in localstorage
    var entries_array = JSON.parse(localStorage.getItem("Entry"));

    //Add new entry to the array
    entries_array.push(entry);

    //Store array
    localStorage.setItem("Entry", JSON.stringify( entries_array ) );
}

console.log(JSON.parse(localStorage.getItem("Entry")));
//Output Array of objects 
//[Object, Object, Object]

希望这有帮助。