javascript - 在javascript中更改foreach循环的键值
问题描述
我想在 javascript 中更改 foreach 循环的键值。
response.forEach(function (item, index) {
<a data-id="+index+"></a>
});
假设如果页面为 1,则索引应从 0 开始,如果页面为 2,则应从 31 开始,如果页面为 3,则索引应从 61 开始。
有可能吗?
例子
在我的 html 中,我增加了data-id
on 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 继续编号
解决方案
也许您只需要跟踪您设置的最后一个索引并增加它。
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>
});
希望这是你所期望的
推荐阅读
- c - 如何在gdb中进行基本参数传递
- python - Python:如何使用不同的图像输入自动重复
- eleventy - Eleventy 没有为从嵌套 index.md 文件生成的索引文件添加 html 后缀
- javascript - Vue路由器条件重定向?
- python - 安装和使用 Python egg 文件
- c++ - 有没有办法在 C++ 中创建多个控制台?
- python - 如何在字符串中动态更改变量的值?
- python - 被 CORS 策略阻止:No"Access-Control-Allow-Origin" Using Flask
- vue.js - Vue 组合 API 监视对象
- python - 如何正确使用 sql alchemy 的 ~ 或 notin_ 子句?