首页 > 解决方案 > 重置本地存储列表的计数器

问题描述

所以这个脚本所做的就是按照列表的顺序将元素的值更改为每个新值。所以它以“item_1”开始,以“item_3”结束,以便在每次页面刷新时更改。每次页面刷新后,值都会按顺序更改。现在,我想知道每当它按顺序到达列表末尾时,在最后一个值之后它才开始显示元素的默认值。并且不会将列表的计数器重置回开头(item_1)。我真的希望它将计数器重置为第一个值并重新开始。

HTML:

<h1 id="text_container">defalut text</h1>

Javascript:

    $(document).ready(function(){
        var list=["item_1","item_2","item_3"];
        // if its first run , we sure localStorage.getItem("counter") is not exists,so we set it to 1 
        if(!(localStorage.getItem("counter_x"))){
            $("#text_container").html(list[0]);
            localStorage.setItem("counter_x","1");
            //we passed 1 as a string so we will need to convert it to number every time we use (later)
        }else if(localStorage.getItem("counter_x")){
            //if it exists , so its not first run and base on the number which is exists, we show item from list:
            $("#text_container").html(list[Number(localStorage.getItem("counter_x"))]);
            //increase the counter:
            var l =Number(localStorage.getItem("counter_x"))+1;
            //for making sure, i pass number as string, but may work by numbers:
            localStorage.setItem("counter_x",l.toString());
        };
        
        
        //it may throw error for when its 5th reloading becuse list.length is smaller than that , but you can solve this simply.

    });

标签: javascripthtml

解决方案


检查您的计数是否是数组的最后一个位置。如果是,则重置您的计数器。

如果counter == array.length - 1然后重置。


推荐阅读