开发者

Local Storage - HTML5 Demo with Code [closed]

开发者 https://www.devze.com 2023-01-30 18:00 出处:网络
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.

开发者_如何学Go

Closed 7 years ago.

Improve this question

I am trying to work with local storage with forms using html5. I am just unable to find a single working demo online. Can anyone find me a good demo and a tutorial that works. My browser is completely supported.

Appreciate all the help. Thanks


Here's a jsfiddle demo

(copy of the associated js code, uses of localStorage are called out in the comments)

//Note that if you are writing a userscript, it is a good idea
// to prefix your keys, to reduce the risk of collisions with other 
// userscripts or the page itself.
var prefix = "localStorageDemo-";

$("#save").click(function () { 
    var key = $("#key").attr('value');
    var value = $("#value").attr('value');
    localStorage.setItem(prefix + key, value);      //******* setItem()
    //localStorage[prefix+key] = value; also works
    RewriteFromStorage();
});

function RewriteFromStorage() {
    $("#data").empty();
    for(var i = 0; i < localStorage.length; i++)    //******* length
    {
        var key = localStorage.key(i);              //******* key()
        if(key.indexOf(prefix) == 0) {
            var value = localStorage.getItem(key);  //******* getItem()
            //var value = localStorage[key]; also works
            var shortkey = key.replace(prefix, "");
            $("#data").append(
                $("<div class='kvp'>").html(shortkey + "=" + value)
                   .append($("<input type='button' value='Delete'>")
                           .attr('key', key)
                           .click(function() {      //****** removeItem()
                                localStorage.removeItem($(this).attr('key'));
                                RewriteFromStorage();
                            })
                          )
            );
        }
    }
}

RewriteFromStorage();


Here is an example of HTML5's LocalStorage.

Here is a fiddle http://jsfiddle.net/ccatto/G2SyC/2/ code demo example.

A simple code would be:

// saving data into local storage
localStorage.setItem('LocalStorageKey', txtboxFooValue);

// getting data from localstorage
var retrivedValue = localStorage.getItem('LocalStorageKey', retrivedValue);

Here is a more complete code example where you enter text into a textbox and click a button. Then the text is stored into LocalStorage and retrieved and displayed in a div.

<h2>HTML LocalStorage Example</h2>

<section>
    <article>
        Web Storage example:
        <br />
        <div id="divDataLocalStorage"></div>
        <br />
        Value
        <input type="text" id="txtboxFooExampleLocalStorage" />
        <input type="button" id="btnSaveToLocalStorage" value="Save Text to Local Storage" />
    </article>
</section>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript">    
    console.log("start log");  
    $("#btnSaveToLocalStorage").click(function () {
        console.log("inside btnSaveToLocalStorage Click function");
        SaveToLocalStorage();
    });

    function SaveToLocalStorage(){
        console.log("inside SaveToLocalStorage function");
        var txtboxFooValue = $("#txtboxFooExampleLocalStorage").val();
        console.log("text box Foo value  = ", txtboxFooValue);
        localStorage.setItem('LocalStorageKey', txtboxFooValue);
        console.log(" after setItem in LocalStorage");
        RetrieveFromLocalStorage();
    }

    function RetrieveFromLocalStorage() {
        console.log("inside Retrieve from LocalStorage");
        var retrivedValue = 'None';
        var retrivedValue = localStorage.getItem('LocalStorageKey', retrivedValue);
        $("#divDataLocalStorage").text(retrivedValue);
        console.log("inside end of retrieve from localstorge");
        console.log("retrieved value = ", retrivedValue);
    }

</script>

Hope this helps!


Have a look at MDC - DOM Storage or W3C's Webstorage draft (ok, less demo and more description). But the API is not that huge.


Local Storage is part of the HTML5 APIs - it is an object and we can access this object and its functionality via JavaScript. During this tutorial, we will use JavaScript to take a look at the fundamentals of the local storage object and how we can store and retrieve data, client side.

Local storage items are set in key/value pairs, so for every item that we wish to store on the client (the end user’s device), we need a key—this key should be directly related to the data that it is stored alongside.

There are multiple methods and an important property that we have access to, so let’s get started.

You would type this code into a HTML5 document, inside your script tags.

Setting Items

First up, we have the setItem() method, which takes our key/ value (or sometimes referred to as name/ value) pair as an argument. This method is very important, as it will allow us to actually store the data on the client; this method has no specific return value. The setItem() method looks just like this:

localStorage.setItem("Name", "Vamsi");

Getting Items

Now that we have had a look at storing some data, let’s get some of that defined data out of local storage. To do this, we have the getItem() method, which takes a key as an argument and returns the string value that is associated with it:

localStorage.getItem("Name");

Removing items

Another method of interest to us is the removeItem() method. This method will remove Items from local storage (we will talk a little more about ‘emptying’ local storage later). The removeItem() method takes a key as an argument and will remove the value associated with that key. It looks just like this:

localStorage.removeItem("Name");

Here is the sample example.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Local Storage</title>
        <script>
            localStorage.setItem("Name", "Vamsi");
            localStorage.setItem("Job", "Developer");
            localStorage.setItem("Address", "123 html5 street");
            localStorage.setItem("Phone", "0123456789");
            console.log(localStorage.length);
            console.log(localStorage.getItem("Name"));
            localStorage.clear();
            console.log(localStorage.length);
        </script>
    </head>
    <body>
    </body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消