首页 > 解决方案 > 在javascript中更改foreach循环的键值

问题描述

我想在 javascript 中更改 foreach 循环的键值。

response.forEach(function (item, index) { 
<a data-id="+index+"></a>    
});

假设如果页面为 1,则索引应从 0 开始,如果页面为 2,则应从 31 开始,如果页面为 3,则索引应从 61 开始。

有可能吗?

例子

在我的 html 中,我增加了data-idon foreach 循环的值。而且我还在页面滚动上附加数据。所以每次我滚动页面时,索引都从 0 开始。这就是为什么我想跳过前一个滚动的数字。

结果与我的代码:

<a data-id="0"></a>
<a data-id="1"></a>
<a data-id="2"></a>
<a data-id="3"></a>
<a data-id="4"></a>
....
<a data-id="30"></a>
<a data-id="0"></a>

所以你看到索引再次从 0 开始所以我想跳过 30 并从 31 继续编号

标签: javascript

解决方案


也许您只需要跟踪您设置的最后一个索引并增加它。

IE 是这样的。

// this should be placed in a way that is 'global' to your module, so it remains evaluated. 
//It starts from -1 because so at first element added it becames 0
var maxIdx=-1; 

response.forEach(function (item, index) {
maxIdx++;
<a data-id="+maxIdx+"></a>    
});

希望这是你所期望的


推荐阅读