如何将localstorage与jquery一起使用(if-else)

时间:2013-08-11 14:11:04

标签: jquery

我有一个html页面和简单的jquery代码。我想在帖子附近添加“阅读/未阅读”文字。当我单击未读文本时,它将被读取并再次单击读取文本,它将变为未读。我想保存我的jquery更改。我可以更改已读/未读文本,但我无法使用localStorage保存更改。每次文本变为“未读”时刷新页面。我的代码需要一些恢复。这些是我的代码。不是:我使用jinja2没有数据库没有服务器只是本地。谢谢你的时间。

  <html>
    <head>
    <title>{{ title }}</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    </head>
    <body>

    <script>

   $(function() {
    $('h4').on('click', function(event) {
        var $this = $(this);
        $(this).text(localStorage.getItem('read'));
        if ($this.text()==="unread"){
           localStorage.setItem('read', 'read');
        }
        else if ($this.text()==="read"){
           localStorage.setItem('read', 'unread');
        }
    });
});
    </script>


    {% for data in collecteddata %}
        <div align="center" class="box">{{ data }}</div><h4>unread</h4>
    {% endfor %}

    </body>
    </html>

3 个答案:

答案 0 :(得分:1)

使用setItem()之类的

$(this).text(localStorage.getItem('read'));
if ($this.text()==="unread"){
    localStorage.setItem('read','read');
}
else if ($this.text()==="read"){
    localStorage.setItem('read','unread');
}

答案 1 :(得分:0)

您需要使用setItem() - 设置值和getItem() - 读取值

$(function() {
    var $h4 = $('h4').on('click', function(event) {
        var $this = $(this), text = $.trim($this.text());
        if (text === "unread"){
            localStorage.setItem('read', 'read');
        } else if (text === "read"){
            localStorage.setItem('read', 'unread');
        }
        $(this).text(localStorage.getItem('read'));
    });

    var text = localStorage.getItem('read');
    if(text){
        $h4.text(text);
    }
});

演示:Fiddle

答案 2 :(得分:0)

本地存储作为密钥:值对。以下是基础知识: - 例如。;

localStorage.setItem("key", "value");  // to store value in, by unique key
var value = localStorage.getItem("key"); // retreive value by key name
相关问题