当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


HTML Storage length用法及代码示例


HTML DOM中的Storage length属性用于返回存储在存储对象中的项目数。存储对象包括localStorage或sessionStorage。

用法:
获取存储长度属性。

object.length

返回值:它返回一个数字,指示存储对象中当前的项目数。


示例1:在localStorage对象上使用。

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>DOM Storage length</title> 
</head> 
  
<body> 
    <h1 style="color:green"> 
      GeeksForGeeks 
  </h1> 
    <b>DOM Storage length</b> 
    <p>Click on the buttons below to add/clear 
      items and check the current number  
      of items in localStorage 
  </p> 
    <p>Total Items:<span class="output"></span></p> 
    <button onclick="addItem(50)"> 
      Add 50 items 
  </button> 
    <button onclick="clearItems()"> 
      Clear all items 
  </button> 
    <button onclick="getStorageLength()"> 
      Get Storage length 
  </button> 
    <div class="items"> </div> 
    <script> 
        // To set item. 
        function addItem(values) { 
            for (i = 0; i < values; i++) 
                localStorage.setItem(i, 'item ' + i); 
        } 
  
        // To clear item.       
        function clearItems() { 
            localStorage.clear(); 
        } 
  
        // To return the number of items. 
        function getStorageLength() { 
            totalItems = localStorage.length; 
            document.querySelector('.output').textContent =  
            totalItems; 
        } 
    </script> 
</body> 
  
</html>

输出:添加50个元素并单击按钮之后。
localstorage

示例2:在sessionStorage对象上使用

<!DOCTYPE html> 
<html> 
  
<head> 
    <title>DOM Storage length</title> 
</head> 
  
<body> 
    <h1 style="color:green"> 
      GeeksForGeeks 
  </h1> 
    <b>DOM Storage length</b> 
    <p> 
      Click on the buttons below to add/clear 
      items and check the current number of 
      items in sessionStorage 
  </p> 
    <p>Total Items:<span class="output"></span></p> 
    <button onclick="addItem(10)">Add 10 items</button> 
    <button onclick="clearItems()">Clear all items</button> 
    <button onclick="getStorageLength()"> 
      Get Storage length 
  </button> 
    <div class="items"> </div> 
  
    <script> 
        function addItem(values) { 
            for (i = 0; i < values; i++) 
                sessionStorage.setItem(i, 'item ' + i); 
        } 
  
        function clearItems() { 
            sessionStorage.clear(); 
        } 
  
        function getStorageLength() { 
            totalItems = sessionStorage.length; 
            document.querySelector('.output').textContent =  
              totalItems; 
        } 
    </script> 
</body> 
  
</html>

输出:添加10个元素后,单击按钮。
sessionStorage

支持的浏览器:下面列出了存储长度属性支持的浏览器:

  • 谷歌浏览器4.0
  • Internet Explorer 8.0
  • Firefox 3.5
  • Opera 10.5
  • Safari 4.0


相关用法


注:本文由纯净天空筛选整理自sayantanm19大神的英文原创作品 HTML | DOM Storage length Property。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。