2012-09-26 29 views
0

我下foo.com/test1/test1.html 1個網站,另一個在foo.com/test2/test2.html獨立localstorages

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的值是「測試1」,如果我去test2的名字將測試2 。基本上我懷疑我需要以不同的名稱命名,但我寧願不這樣做。有沒有什麼好的解決方法?

預先感謝您。

+0

爲什麼不使用HTTP_REFERER? – stark

+0

現階段不允許使用PHP或任何服務器端腳本。你會更詳細地表達這一點嗎? –

+1

LocalStorage設置爲每個域,所以不,你不能這樣做。爲什麼不簡單使用不同的名字?或者 - 如果您希望代碼儘可能相似,請使用JavaScript變量來存儲前綴,例如:ugh,讓人討厭「Enter to save」 - 假設您有:var prefix =「test1」。然後,當你得到/設置項目,做:localStorage.getItem(前綴+「名稱」) –

回答

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> 

類似於所有頁面。

+0

謝謝。我的解決方案與此類似。 –