Javascript 如何检查HTML会话存储是否为空?
G'day伙计们 我正试图找出在HTML5中检查空Javascript 如何检查HTML会话存储是否为空?,javascript,html,Javascript,Html,G'day伙计们 我正试图找出在HTML5中检查空storageSession的最佳方法 我注意到,如果清除或未将任何值设置到会话存储,一些浏览器会返回null,而另一些浏览器只返回空白 我试过以下方法 if (sessionStorage.getItem('value1') == "null" && sessionStorage.getItem('value2') == "null") { 但它似乎不起作用 有谁有更好的方法来检查会话存储空间是否为空 感谢您在这方面的帮助,并
storageSession
的最佳方法
我注意到,如果清除或未将任何值设置到会话存储
,一些浏览器会返回null,而另一些浏览器只返回空白
我试过以下方法
if (sessionStorage.getItem('value1') == "null" && sessionStorage.getItem('value2') == "null") {
但它似乎不起作用
有谁有更好的方法来检查会话存储空间是否为空
感谢您在这方面的帮助,并提前向您表示感谢。这应该行得通;问题是引号中有null
另外,sessionStorage.length将提供存储的值的数量。但这是检查“空”会话存储的方式
if (sessionStorage.length == 0) {
你也可以试试
if($window.sessionStorage.value === undefined) {}
使用此选项检查是否存在名为“name”的会话存储项
我是这样检查的
$(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;
}
在这种情况下,我使用:
if(sessionStorage.getItem('value1').length==0){}
Hi Herohtar,感谢您向我指出错误。非常感谢。对于一些浏览器返回null和一些返回空白的情况,我们应该创建2个条件语句吗?一个为空,一个为空?如果您需要同时检查这两个,那么您必须这样做。出于好奇,哪个浏览器返回空白?如果未设置该值,则getItem()应始终返回null。另外,请参阅我对答案的补充,了解另一个可能的测试;如果它为空,大多数浏览器都会将其呈现为null。然而,对于文本输入来说,情况就不同了。IE将在文本框中包含null一词作为值。使用typeof sessionStorage['name']=='undefined'对meI有效。我认为您不能在null上使用.length
$(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;
}