2

我尝试在 localStorage 中输入一个数字,但 ++ 没有其他方式吗?

window.localStorage.setItem('run','++')

这是完整的代码

<script type="text/javascript">
    if(window.localStorage.getItem('run')==null){

        window.localStorage.setItem('run','1')
    }
    else if(window.localStorage.getItem('run')==1){

        window.localStorage.setItem('run','++')
        window.location = "index_aerosoft.html";
    }
    else if(window.localStorage.getItem('run')==25){

        alert("hey 25times");
        window.localStorage.setItem('run','null')
    };
</script>
4

3 回答 3

3

localStorage只包含字符串。

如果要在其中保留一个计数器,则必须对其进行解析:

var c = parseInt(localStorage['run']||'0', 10); // read, with 0 as default value
c++; // increment
localStorage['run'] = c; // store the incremented value
于 2013-01-23T09:46:23.560 回答
1

本地存储只存储字符串。而且它不能将参数解析为表达式来动态增加一个值,您必须手动执行此操作。

因此,您首先需要获取该值并将其解析为整数:

i = parseInt(window.localStorage.getItem('run'));

然后您可以存储增量值:

window.localStorage.setItem('run',(i + 1));

注意:根据您的情况

else if(window.localStorage.getItem('run')==1){

您检查 a1是否已存储,我想您缩进检查该值是否小于 25?如果不是,则增加该值是没有意义的,因为以下语句将始终存储 2...

于 2013-01-23T09:51:47.560 回答
0

if(window.localStorage.getItem('run')==null){

        window.localStorage.setItem('run','1');
        alert("First start");
    }else if(window.localStorage.getItem('run')==10){

        window.localStorage.setItem('run','1');
    }else{

        var run = window.localStorage.getItem('run');
        var irun;
        irun = (parseInt(run) + 1);
        window.localStorage.setItem('run',irun.toString());
        window.location = "index_xyz.html";
        alert(window.localStorage.getItem('run'));
    }

</script>
于 2013-01-23T10:15:57.383 回答