为了账号安全,请及时绑定邮箱和手机立即绑定

有没有办法简化 document.getElementById ?

有没有办法简化 document.getElementById ?

不负相思意 2024-01-18 20:42:13
我的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 多个答案变量。
查看完整描述

3 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

只需使用单个数组变量来保存所有问题,而不是单个变量:


// 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);

}

然后,您可以使用 examplequestions[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 在他的答案中提到的类。


查看完整回答
反对 回复 2024-01-18
?
白板的微信

TA贡献1883条经验 获得超3个赞

如前所述,您可以使用循环和数组:


let questions = [];

for (let i = 0; i < 8; ++i) {

  questions.push(document.getElementById(i));

}

您循环遍历某个合适的范围 - 并在每次迭代中附加到数组。


然后,您可以像这样访问特定的“问题”:


console.log(questions[4]);


查看完整回答
反对 回复 2024-01-18
?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

添加class="question"到每个问题而不是id=1id=2等,然后使用document.querySelectorAll(".question")获取包含页面上所有问题的类似数组的对象。

var questions = document.querySelectorAll(".question");
// now you can reference every question with questions[0] thru questions[n-1]


查看完整回答
反对 回复 2024-01-18
  • 3 回答
  • 0 关注
  • 34 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信