本地存储 - HTML5 演示与代码

发布于 2024-10-08 14:40:49 字数 1539 浏览 10 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

水中月 2024-10-15 14:40:49

这是一个 jsfiddle 演示

(相关js代码的副本,localStorage的使用在注释中指出)

//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'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();
執念 2024-10-15 14:40:49

这是 HTML5 LocalStorage 的示例。

这是一个小提琴 http://jsfiddle .net/ccatto/G2SyC/2/ 代码演示示例。

一个简单的代码如下:

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

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

这是一个更完整的代码示例,您可以在文本框中输入文本并单击按钮。然后文本被存储到 LocalStorage 中并检索并显示在 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>

希望这有帮助!

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!

揪着可爱 2024-10-15 14:40:49

查看 MDC - DOM 存储W3C 的 Webstorage 草案(好的,演示较少,描述较多)。但 API 并没有那么大。

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.

微凉 2024-10-15 14:40:49

本地存储是 HTML5 API 的一部分 - 它是一个对象,我们可以通过 JavaScript 访问该对象及其功能。在本教程中,我们将使用 JavaScript 来了解本地存储对象的基础知识以及如何在客户端存储和检索数据。

本地存储项目以键/值对的形式设置,因此对于我们希望存储在客户端(最终用户的设备)上的每个项目,我们需要一个密钥 - 该密钥应该与其存储在一起的数据直接相关。

我们可以访问多种方法和一个重要属性,所以让我们开始吧。

您可以将此代码键入 HTML5 文档中的脚本标记内。

设置项目

首先,我们有 setItem() 方法,它将我们的键/值(或有时称为名称/值)对作为参数。这个方法非常重要,因为它允许我们将数据实际存储在客户端上;该方法没有具体的返回值。 setItem() 方法如下所示:

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

获取项目

现在我们已经了解了一些数据的存储,接下来让我们从本地存储中获取一些已定义的数据。为此,我们使用 getItem() 方法,该方法将键作为参数并返回与其关联的字符串值:

localStorage.getItem("Name");

删除项目

我们感兴趣的另一个方法是 removeItem() 方法。此方法将从本地存储中删除项目(稍后我们将详细讨论“清空”本地存储)。 removeItem() 方法将一个键作为参数,并将删除与该键关联的值。它看起来像这样:

localStorage.removeItem("Name");

这是示例示例。

<!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>

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文