gpt4 book ai didi

javascript - 有没有办法简化 document.getElementById?

转载 作者:行者123 更新时间:2023-12-04 01:08:55 26 4
gpt4 key购买 nike

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

关于javascript - 有没有办法简化 document.getElementById?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65444351/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com