javascript - 重置本地存储列表的计数器
问题描述
所以这个脚本所做的就是按照列表的顺序将元素的值更改为每个新值。所以它以“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.
});
解决方案
检查您的计数是否是数组的最后一个位置。如果是,则重置您的计数器。
如果counter == array.length - 1
然后重置。
推荐阅读
- python - Where is the __call__() in tensorflow/contrib/cudnn_rnn/python/layers/cudnn_rnn.py
- playframework-2.6 - 无法从单元测试中的消息文件中读取消息
- java - Bottom Sheet Dialog for RecyclerView Item Click
- crash - Spyder 在 Linux 上启动时崩溃并出现 QtWebEngineCore 错误
- c# - WPF 文本更改事件未在“S”上触发
- vba - Excel VBA在特定值后的空白单元格中添加值
- sql-server - M/D/YYYY h:mm tt 到 DATETIME SQL Server
- javascript - 使用 parseInt() 函数将字符串转换为 int 时出现问题
- ruby-on-rails - Passing Local Variable in Rails 5 Best Practice
- python - 尝试使用 captsone 与 winappdbg 进行反汇编时出错