如何为JavaScript变量分配本地存储变量?
这是我的尝试:
var abc=localStorage.crabc;
function tab()
{
if (abc==2) {
window.open("index.html","_self")
} else {
window.open("main.html","_self")
}
}
tab()
localStorage.crabc="2";
答案 0 :(得分:3)
tab()
答案 1 :(得分:1)
您需要使用localStorage.getItem()
和localStorage.setItem()
检索项目并将其存储到localStorage:
var abc=localStorage.getItem('crabc');
function tab()
{
if (abc=='2') {
window.open("index.html","_self")
} else {
window.open("main.html","_self")
}
}
tab();
localStorage.setItem('crabc', '2');
答案 2 :(得分:1)
试试这个Demo here
function tab() {
var check = window.localStorage.getItem("visitedBefore");
if (check) {
alert('already visited');
window.open("index.html", "_self")
} else {
alert('first time visited');
window.open("main.html", "_self")
}
window.localStorage.setItem("visitedBefore", true);
}
HTML:
<input type="button" value="redirect" onclick="tab()" />