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 に行くと name の値が「test1」になり、test2 に行くと name が test2 になるということを達成できるかということです。基本的に、別の名前を付ける必要があると思いますが、そうしません。これに対する良い回避策はありますか?

前もって感謝します。

4

1 に答える 1

0

ローカル ストレージはドメインごとに定義されます。ページのコンテキストを維持するには、オブジェクトを localstorage に保持する必要があります。

ここにそれを行うための解決策があります。

<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 に答える