0

我在 foo.com/test1/test1.html 下有 1 个站点,在 foo.com/test2/test2.html 下有另一个站点

test1.html 看起来像这样:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
        document.ready = function(){
            var name = localStorage.getItem("name");
            if(name){
                console.log("name is defined");
            }else{
                console.log("name is not defined");
                localStorage.setItem("name", "test1");
            }
            $('#name').text(name);
        }
    </script>
</head>
<body>
    <p id="name"></p>
</body>
</html>

而test2.html是这样的:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
        document.ready = function(){
            var name = localStorage.getItem("name");
            if(name){
                console.log("name is defined");
            }else{
                console.log("name is not defined");
                localStorage.setItem("name", "test2");
            }
            $('#name').text(name);
        }
    </script>
</head>
<body>
    <p id="name"></p>
</body>
</html>

我的问题是,如果我去 test1,名字的值是“test1”,如果我去 test2,名字将是 test2,是否有可能实现。基本上我怀疑我需要以不同的方式命名它们,但我宁愿不这样做。有什么好的解决方法吗?

先感谢您。

4

1 回答 1

0

本地存储是按域定义的。您应该将对象保存在本地存储中以维护页面上下文。

这是解决方案。

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
    <script>
        document.ready = function(){
            var thispage = JSON.parse(localStorage.getItem("page1"));
            if(thispage.name){
                console.log("name is defined");
            }else{
                console.log("name is not defined");
                var obj={name : "test1"}

                localStorage.setItem("page1", JSON.stringify(obj));
            }

        }
    </script>
</head>
<body>
    <p id="name"></p>
</body>
</html>

类似于所有页面。

于 2012-09-27T07:56:51.667 回答