[英]Is there a way to simplify 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 並查詢問題,例如使用 class 作為 PHP Guru 在他的回答中提到的問題。
如前所述,您可以使用循環和數組:
let questions = [];
for (let i = 0; i < 8; ++i) {
questions.push(document.getElementById(i));
}
您在每次迭代中循環某個合適的范圍 - 和 append 到數組。
然后,您可以像這樣訪問特定的“問題”:
console.log(questions[4]);
將class="question"
添加到每個問題,而不是id=1
、 id=2
等,然后使用document.querySelectorAll(".question")
獲取像 object 這樣的數組,其中包含頁面上的所有問題。
var questions = document.querySelectorAll(".question");
// now you can reference every question with questions[0] thru questions[n-1]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.