1

我有一个 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>
4

3 回答 3

1

使用setItem() 之类的

$(this).text(localStorage.getItem('read'));
if ($this.text()==="unread"){
    localStorage.setItem('read','read');
}
else if ($this.text()==="read"){
    localStorage.setItem('read','unread');
}
于 2013-08-11T14:12:26.620 回答
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);
    }
});

演示:小提琴

于 2013-08-11T14:13:42.997 回答
0

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

localStorage.setItem("key", "value");  // to store value in, by unique key
var value = localStorage.getItem("key"); // retreive value by key name
于 2013-08-11T14:17:47.760 回答