如何检查HTML sessionStorage是否为空?

时间:2011-01-16 09:56:47

标签: javascript html5

G'day伙计们,

我正在尝试找出在HTML5中检查空storageSession的最佳方式。

我注意到有些浏览器返回null,如果你清除或没有为sessionStorage设置任何值,有些浏览器只返回空格。

我尝试了以下

if (sessionStorage.getItem('value1') == "null" && sessionStorage.getItem('value2') == "null") {

但它似乎不起作用。

任何人都有更好的方法来检查sessionStorage是否为空?

感谢您对此的帮助,并提前感谢您。

6 个答案:

答案 0 :(得分:13)

那应该有用;问题是你的引号中有 null

此外,sessionStorage.length将为您提供存储的值的数量。

答案 1 :(得分:5)

但这是你检查“空”会话存储

的方法
   if (sessionStorage.length == 0) {

答案 2 :(得分:3)

使用此选项检查是否存在名为" name"

的会话存储项
if (sessionStorage['name']) {
    console.log("There is 'name' in session storage ")
}

答案 3 :(得分:1)

您也可以尝试

    if($window.sessionStorage.value === undefined) {}

答案 4 :(得分:0)

我检查过这种方式

   $(document).ready(function () {
       if (window.sessionStorage) {
           if (sessionStorage.getItem("x-mas") === null) {
               if (getCountryCode() == 'de') {
                   $('#xmasModal').modal();
                   sessionStorage.setItem("x-mas", "1")
               }
           }
       }
   });

   function getCountryCode() {
       var url = window.location.pathname;
       var segments = url.split('/');
       var countrycode = segments[1];
       return countrycode;
   }

答案 5 :(得分:0)

在这种情况下,我使用:

| user_id | game_id | game_detail | user_game_rank |
| ------- | ------- | ----------- | -------------- |
| 6       | 11      | 260         | 1              |
| 6       | 10      | 100         | 2              |
| 7       | 10      | 1200        | 1              |
| 7       | 11      | 500         | 2              |
| 7       | 12      | 260         | 3              |
| 7       | 13      | 50          | 4              |