无法使用localStorage

时间:2016-03-02 10:16:00

标签: javascript jquery html html5 web

为什么本地存储不起作用?

我最近决定在一个我正在研究的小网站上,我想尝试使用可切换的主题。我希望主题能够在会话之后持续存在,而我还没有登录,所以我正在寻找本地存储。

此处的控制台日志确认正在运行该功能,但没有为该页面创建存储空间。

var main = function() {
$('#theme1').click (function () {
    localStorage.setItem("theme", "1");
    console.log("click");
});
}
$(document).ready(main);

我也试过localStorage.theme = "1";无济于事。

我使用的是最新版本的Chrome,但尽管很明显支持html 5,但我已经检查了w3网站w3schools.com/html5_webstorage,并通过他们的"自己试试"系统工作。

2 个答案:

答案 0 :(得分:2)

enter image description here

请参考图像以检查/验证localstorage是否有效。你也写了点击事件的代码...点击它甚至然后在控制台中看到。控制台日志中还有一件事

Sub getDate()
    theErr = 0
    'pick up date:
    theDay = Cells(13, 9).Value
    theMonth = Cells(13, 10).Value
    theYear = Cells(13, 11).Value

    'Convert month name to number:
    If theMonth = "January" Then
        theMonth = 1
    ElseIf theMonth = "February" Then
        theMonth = 2
    ElseIf theMonth = "March" Then
        theMonth = 3
    ElseIf theMonth = "April" Then
        theMonth = 4
    ElseIf theMonth = "May" Then
        theMonth = 5
    ElseIf theMonth = "June" Then
        theMonth = 6
    ElseIf theMonth = "July" Then
        theMonth = 7
    ElseIf theMonth = "August" Then
        theMonth = 8
    ElseIf theMonth = "September" Then
        theMonth = 9
    ElseIf theMonth = "October" Then
        theMonth = 10
    ElseIf theMonth = "November" Then
        theMonth = 11
    ElseIf theMonth = "December" Then
        theMonth = 12
    End If

    'Check manually for bad dates:
    If InStr("2/4/6/9/11", CStr(theMonth)) Then 'a month with 30 or fewer days:
        If theMonth <> 1 Then 'January ("1") is found in 11, but January is OK, it has 31 days...
            If theDay = 31 Then
                Cells(13, 9).Interior.ColorIndex = 38
                theErr = theErr + 1
            End If
            If InStr("2", CStr(theMonth)) Then 'February, with either 28 or 29 days:
                If theDay = 30 Then
                    Cells(13, 9).Interior.ColorIndex = 38
                    theErr = theErr + 1
                ElseIf theDay = 29 Then
                    If theYear Mod 4 <> 0 Then 'not a leap year:
                        Cells(13, 9).Interior.ColorIndex = 38
                        theErr = theErr + 1
                    End If
                End If
            End If
        End If
    End If

    'Give error message if date error picked up:
    If theErr <> 0 Then
        MsgBox "Please check your date", vbOKOnly, "getDate"
        Exit Sub
    End If

    theCurrentDate = DateSerial(theYear, theMonth, theDay)

    If CDate(theCurrentDate) >= CDate(Cells(1, 1)) Then
        'do some stuff
    End If
End Sub

投票,如果你喜欢......

答案 1 :(得分:0)

加载页面时读取本地存储已经有效。

根据Dan Prince的评论,我使用开发人员窗口控制台运行localStorage.theme = "1",看起来它的工作原因并不简单。您必须离开本地存储视图并返回以查看更改,它不会刷新。

我最初查看本地存储的方法是单击地址栏中地址左侧的图标,其中显示了Cookie,本地存储和连接信息。这会立即更新并保留w3schools.org中的本地存储设置,但由于某种原因不会从我的页面读取本地存储。