HTML DOM 儲存 getItem() 方法


HTML DOM 儲存 getItem() 方法用於透過傳遞給定鍵名來獲取儲存物件。它將返回鍵的值,如果不存在具有該給定名稱的鍵,則將返回 NULL。

語法

以下是 Storage getItem() 方法的語法 -

localStorage.getItem(keyname);

sessionStorage.getItem(keyname);

其中,keyname 是字串型別,表示要獲取的項的名稱。

示例

讓我們看一個 HTML DOM 儲存 getItem() 方法的示例 -

即時演示

<!DOCTYPE html>
<html>
<body>
<h1 style="text-align:center">Storage getItem() method example</h1>
<p>Create a localStorage item with the name CLICKS to count the number of clicks on the create button by clicking the below button</p>
<button onclick="createItem()">CREATE</button>
<p>Get the CLICKS item value by clicking the below button</p>
<button onclick="showItem()">Display</button>
<p id="Sample"></p>
<script>
   var y=1;
   function createItem() {
      document.getElementById("Sample").innerHTML="localStorage Item has been created with name CLICKS";
      localStorage.visits = y;
      y++;
   }
   function showItem() {
      var x = localStorage.getItem("visits");
      document.getElementById("Sample").innerHTML = "The total no. of clicks are : "+x;
   }
</script>
</body>
</html>

輸出

這將產生以下輸出 -

點選 CREATE 按鈕 -

點選“Display”按鈕 -

更新於: 19-Feb-2021

84 次瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始吧
廣告