3 回答

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 在他的答案中提到的類。

TA貢獻1883條經驗 獲得超3個贊
如前所述,您可以使用循環和數組:
let questions = [];
for (let i = 0; i < 8; ++i) {
questions.push(document.getElementById(i));
}
您循環遍歷某個合適的范圍 - 并在每次迭代中附加到數組。
然后,您可以像這樣訪問特定的“問題”:
console.log(questions[4]);

TA貢獻2021條經驗 獲得超8個贊
添加class="question"
到每個問題而不是id=1
、id=2
等,然后使用document.querySelectorAll(".question")
獲取包含頁面上所有問題的類似數組的對象。
var questions = document.querySelectorAll(".question"); // now you can reference every question with questions[0] thru questions[n-1]
添加回答
舉報