2017-09-07 39 views
1

我做了一些HTML/Javascript代碼是這樣的:localStorage的工作不

<script> 
if(window.localStorage!==undefined) 
{ 
} 
else{ alert('Your browser is outdated!'); } 
function myfunction1{ 
if(localStorage.getItem('permission')!="") { localStorage.setItem('permission', pressed);} 
function myfunction2{ document.getElementById('data').innerHTML = localStorage.getItem('permission');} 
</script> 
<body onload="myfunction2()"> 
<p id="data">this paragraph shows storage data</p> 
<button onclick="myfunction1()">press</button> 

第一個腳本是用於檢查瀏覽器是否支持localStorage的。 第二個腳本(myfunction1)檢查是否有任何數據被稱爲「許可」。如果沒有,那麼它會成爲一個。 第三個代碼(myfunction2)用於顯示本地存儲數據。 但這些都沒有工作。也許在我的代碼中存在一個簡單的問題。但我無法修復它。請幫忙。

回答

0

你在你的代碼的幾個語法錯誤:

  1. 您可以檢查無論您的Web瀏覽器支持的localStorage與否,只是做typeof(Storage) === "undefined",工程的localStorage/sessionStorage的。
  2. 你的函數需要正確的語法即function name() {handle}
  3. 你沒有定義按下,如果一個字符串是你需要什麼,你忘了雙引號"pressed"周圍。

<script> 
 
if(typeof(Storage) === "undefined") { 
 
    alert('Your browser is outdated!'); 
 
} 
 

 
function myfunction1() { 
 
    if(localStorage.getItem('permission')!="") 
 
    { localStorage.setItem('permission', 'pressed');} 
 
} 
 

 
function myfunction2() { 
 
    document.getElementById('data').innerHTML = localStorage.getItem('permission'); 
 
} 
 

 
</script> 
 

 
<body onload="myfunction2()"> 
 
<p id="data">this paragraph shows storage data</p> 
 
<button onclick="myfunction1()">press</button> 
 
</body>

+0

你的代碼有什麼,我需要。但是你的代碼有一個錯誤。 if(typeof(Storage)!==「undefined」){alert('您的瀏覽器已過時!'); }:如果typeof(存儲)未定義,此代碼用於發出警報。或者如果定義了typeof(存儲)。將其更改爲if(typeof(Storage)==「undefined」){alert('Your browser is old!'); } – user8575948

+0

當我打開頁面(其中包含您的答案中的代碼)時,我的瀏覽器每次都警告「您的瀏覽器已過時」。但是本地存儲設置和getitem正在完美運行。 – user8575948

+0

我會選擇你的答案爲正確的。但要求您編輯答案,以便對其他訪問者有所幫助。 – user8575948