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


不负相思意
浏览 41回答 3
3回答

HUWWW

只需使用单个数组变量来保存所有问题,而不是单个变量:// initialize a variable to be an empty arrayvar questions = [];// create a loop which assigns value 1 to 9 into the variable ifor (let i = 1; i < 10; i++) {&nbsp; &nbsp; // assign the content of the element with ID i to i-th element of the array&nbsp; &nbsp; questions[i] = document.getElementById(i);}然后,您可以使用 examplequestions[5]代替question5.如果您对 HTML 元素进行非顺序命名,则可以使用包含元素 ID 列表的数组:// define a list of element IDslet htmlIds = ['id1', 'ab', 'xy', 'anotherId'];// initialize a variable to be an empty arrayvar questions = [];// go through all items of the htmlIds arrays and populate questionshtmlIds.forEach(item => questions[item] = item);但在这种情况下,我会考虑采用不同的方法,您可以忽略 ID 并查询问题,例如使用 PHP Guru 在他的答案中提到的类。

白板的微信

如前所述,您可以使用循环和数组:let questions = [];for (let i = 0; i < 8; ++i) {&nbsp; questions.push(document.getElementById(i));}您循环遍历某个合适的范围 - 并在每次迭代中附加到数组。然后,您可以像这样访问特定的“问题”:console.log(questions[4]);

宝慕林4294392

添加class="question"到每个问题而不是id=1、id=2等,然后使用document.querySelectorAll(".question")获取包含页面上所有问题的类似数组的对象。var&nbsp;questions&nbsp;=&nbsp;document.querySelectorAll(".question"); //&nbsp;now&nbsp;you&nbsp;can&nbsp;reference&nbsp;every&nbsp;question&nbsp;with&nbsp;questions[0]&nbsp;thru&nbsp;questions[n-1]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript