亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

有沒有辦法簡化 document.getElementById ?

有沒有辦法簡化 document.getElementById ?

不負相思意 2024-01-18 20:42:13
我的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 多個答案變量。
查看完整描述

3 回答

?
HUWWW

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


查看完整回答
反對 回復 2024-01-18
?
白板的微信

TA貢獻1883條經驗 獲得超3個贊

如前所述,您可以使用循環和數組:


let questions = [];

for (let i = 0; i < 8; ++i) {

  questions.push(document.getElementById(i));

}

您循環遍歷某個合適的范圍 - 并在每次迭代中附加到數組。


然后,您可以像這樣訪問特定的“問題”:


console.log(questions[4]);


查看完整回答
反對 回復 2024-01-18
?
寶慕林4294392

TA貢獻2021條經驗 獲得超8個贊

添加class="question"到每個問題而不是id=1id=2等,然后使用document.querySelectorAll(".question")獲取包含頁面上所有問題的類似數組的對象。

var questions = document.querySelectorAll(".question");
// now you can reference every question with questions[0] thru questions[n-1]


查看完整回答
反對 回復 2024-01-18
  • 3 回答
  • 0 關注
  • 228 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號