首页 > 解决方案 > 有没有办法简化 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 多个答案变量。

标签: javascriptdomgetelementbyid

解决方案


类似以下内容的情况如何:

// 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 在他的回答中提到的类。


推荐阅读