javascript - 存储迭代计数,然后在 javascript 中的 for 循环之外访问它
问题描述
我想我误解了提升的工作原理,但我对为什么返回的 i++ 没有被提升到 var i 的初始声明感到困惑。对于上下文,我正在尝试创建利用 scrollIntoView() 在 div 之间循环的上一个/下一个按钮。
我让它按预期用于下一个按钮(单击并循环到下一个 div),但问题是我似乎无法将 i 的当前值存储在 for 循环之外,以便我可以在另一个内部使用 stepsTotal[i]函数(用于处理单击时的上一个按钮)。
这是我为下一个按钮工作的代码(不包括上一个按钮功能)。当单击下一个按钮时,我试图让 console.log(i) 打印 0、1、2、3 等。)
const stepsTotal = document.getElementsByClassName("question-steps");
const currentStep = (function() {
var i;
console.log(i); // How do I have this print the current value of i instead of undefined? (i.e. match the results of the second console.log)
for (i=0; i<stepsTotal.length; i++) {
document.getElementById("next-button").addEventListener("click", scrollToCurrentStep);
function scrollToCurrentStep() {
stepsTotal[i].scrollIntoView(true);
i++;
console.log(i); // I want the first console.log to match this one
return
}
return
}
}());
解决方案
推荐阅读
- javascript - Jquery - 如何为多个元素制作绑定点击事件?
- r - 如何从两个数据框创建堆叠和分组条形图?
- debian - avr-gcc:对 char 数组进行迭代不适用于太多迭代
- django - 渲染 Crispy 表单 + 无提交按钮
- kotlin - 如何在 kotlin 的数据类中为辅助构造函数建立 getter 和 setter?
- php - 索引视图无法识别侧边栏视图中的变量
- google-apps-script - Google 表格 - 在保留链接的同时有条件地从另一个表格导入行
- python - Django-taggit 标记值检索和格式化失败
- amazon-web-services - 删除列表 DynamoDB 中的元素
- jquery - 引导日期选择器在输入和弹出日历上显示不同的日期