Javascript 如何检查 HTML sessionStorage 是否不为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4704735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if HTML sessionStorage is not empty?
提问by John Citizen
G'day guys,
G'day 伙计们,
I'm trying to figure out the best way to check for empty storageSession
in HTML5.
我试图找出storageSession
在 HTML5 中检查空值的最佳方法。
I noticed that some browser returns null and some return just empty space if you clear or did not set any values to the sessionStorage
.
我注意到,如果您清除或没有为sessionStorage
.
I've tried the following
我试过以下
if (sessionStorage.getItem('value1') == "null" && sessionStorage.getItem('value2') == "null") {
But it doesn't seem to work.
但它似乎不起作用。
Anyone got a better way to check if a sessionStorage
is empty?
有人有更好的方法来检查 asessionStorage
是否为空吗?
Appreciate your help on this and thank you in advance.
感谢您对此的帮助,并在此先感谢您。
回答by Herohtar
That should work; the problem is that you have nullin quotes.
那应该有效;问题是,你有空引号。
Also, sessionStorage.length
will give you the number of values stored.
此外,sessionStorage.length
会给你存储的值的数量。
回答by selbie
But this is how you check for "empty" session storage
但这就是您检查“空”会话存储的方式
if (sessionStorage.length == 0) {
回答by Marko Reljic
Use this to check if there is item is session storage called "name"
使用它来检查是否有名为“名称”的会话存储项
if (sessionStorage['name']) {
console.log("There is 'name' in session storage ")
}
回答by Sumitra
You can also try
你也可以试试
if($window.sessionStorage.value === undefined) {}
回答by Thomas
i checked this way
我是这样检查的
$(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;
}
回答by Вася Тарарин
In case like this, I use:
在这种情况下,我使用:
if (sessionStorage.getItem('value1').length == 0) {}