當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。