HTML DOM Storage getItem() 方法

htmlweb developmentfront end technology更新于 2024/5/26 18:20:17

HTML DOM Storage getItem() 方法用于通过传递给定的键名来获取存储对象。它将返回键的值,如果没有指定名称的键,则返回 NULL。

语法

以下是 Storage getItem() 方法的语法 −

localStorage.getItem(keyname);

或

sessionStorage.getItem(keyname);

其中,keyname 为字符串类型,表示要获取的项目的名称。

示例

让我们来看一个 HTML DOM Storage 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>

输出

这将产生以下输出 −

点击"创建"按钮 −

点击"显示"按钮 −


相关文章


有用资源