javascript - 有没有办法简化 document.getElementById?
问题描述
我的 javascript 代码超过 300 万行代码,因为我需要调用很多变量,有什么办法可以简化这个吗?
这是代码:
var Start = document.getElementById('Start'),
question1 = document.getElementById('1'),
question2 = document.getElementById('2'),
question3 = document.getElementById('3'),
question4 = document.getElementById('4'),
question5 = document.getElementById('5'),
question6 = document.getElementById('6'),
question7 = document.getElementById('7');
我有 50 多个问题变量和 50 多个答案变量。
解决方案
类似以下内容的情况如何:
// initialize a variable to be an empty array
var questions = [];
// create a loop which assigns value 1 to 9 into the variable i
for (let i = 1; i < 10; i++) {
// assign the content of the element with ID i to i-th element of the array
questions[i] = document.getElementById(i);
}
然后,您可以使用例如questions[5]
代替question5
.
如果您对 HTML 元素进行非顺序命名,则可以使用包含元素 ID 列表的数组:
// define a list of element IDs
let htmlIds = ['id1', 'ab', 'xy', 'anotherId'];
// initialize a variable to be an empty array
var questions = [];
// go through all items of the htmlIds arrays and populate questions
htmlIds.forEach(item => questions[item] = item);
但是在这种情况下我会考虑一种不同的方法,您可以忽略 ID 并查询问题,例如使用 PHP Guru 在他的回答中提到的类。
推荐阅读
- django - 在位于 settings.py 的视图中调用函数
- c# - 使用具有通用查询性能的 AsCacheQueryable 从 Ignite 获取数据
- pandas - Pandas 用预定义的值替换单元格值
- javascript - angular8-surveyjs-如何删除默认完成按钮
- r - RShiny - 在“观察”环境中预测值
- vue.js - 使用 vuetify 水平和垂直居中 v-card 的最佳方式
- angular - 替换子组件时能够设置父 div 样式
- create-react-app - ELIFECYCLE 代码 2 eslint 错误与 create-react-library
- python-3.x - 将 Ipywidgets 与数据框一起使用
- python - 仅当 TensorFlow 模型改进了训练和验证数据时才应用梯度下降