如何在localstorage上保存数据并将此数据附加到某个body元素

时间:2017-08-19 03:09:33

标签: javascript html css client local-storage

我有一个简单的js代码,它添加了一些数据并将其保存在某些HTML标记上,我可以将其添加到localstorage并保存在sesion的某个时间。 有人能告诉我,如何在localstorage上保存数据? 非常感谢你提前做好准备。

        function addComment()
            {
              var vname = document.getElementById("vname").value;
              var li = document.createElement('li');
              li.innerText = vname;
              document.getElementById('comments').appendChild(li);
              document.getElementById("vname").value = '';
              document.getElementById("vname").focus();
            }
        function addAuthor()
        {
            var author = document.getElementById("author").value;
            var li = document.createElement('li');
            li.innerText = author;
            document.getElementById('comments').appendChild(li);
            document.getElementById("author").value = '';
            document.getElementById("author").focus();
        }
        <label for="vname">Name of your book</label>
        <input type="text" id="vname" name="vname">
        <input type="submit" value="Add name" onclick="addComment()">
        <br>
        <label for="author">Author of book</label>
        <input type="text" id="author" name="author">
        <input type="submit" value="Add author" onclick="addAuthor()">

<ul id="comments"></ul>

2 个答案:

答案 0 :(得分:0)

您可以在localStorage中设置值,如下所示

localStorage.setItem("name", "value");

window.localStorage.setItem("name", "value");

你可以像这样追加价值

var value  = localStorage.getItem("name");
$("#div_id").text(value);

OR for input field

$("#input_field_id").val(value);

window.localStorage.getItem("name");

我这个window.localStorage是针对angularjs我不确定

答案 1 :(得分:0)

首先,您需要检查浏览器支持或不支持localStorage

   if (typeof(Storage) !== "undefined") {
    //if your browser support localstorage then you can write code like this

    localstorage.setItem("your key", JSON.stringify(your value));

} else {
// sorry you can't use localstorage

}
设置值后

你可以像这样访问你的价值

var your_variable = JSON.parse(localstorage.getItem("your key"));