白衣染霜花
2023-11-11 21:46:08
我正在創建一個導航列表,每當將新的部分元素添加到頁面時,該列表就會動態填充。我首先創建了一個空數組,其目的是通過對其應用 forLoop 來連續接收頁面上添加的內容。這是 JavaScript 代碼 var list= document.getElementById('navbar__list'); let myArray= []; //Create an empty arrayfor( let i=0; i<=myArray.length; i++){ var triggerSection= document.getElementById('section'+(1+i)); //Call section elements one by one with id=section(1+i) myArray.push(triggerSection); //push elements to create an array that includes all sections on the page var sectionName= myArray[i].getAttribute('data-nav'); //Call data-nav value for each item const newItem= document.createElement('Li'); //create li elemnt inside the document object newItem.textContent= sectionName; //pass the data-nav value as a text to the li element newItem.setAttribute('id','item'+(1+i)); list.appendChild(newItem); //pass the li element to the unordered list}HTML 代碼<ul id="navbar__list"> </ul><section id="section1" data-nav="Section 1" class="your-active-class"><section id="section2" data-nav="Section 2"><section id="section3" data-nav="Section 3">問題是,當設置如上所示的 for 循環的結束條件時,它會在數組末尾添加一個值為 (null) 的額外元素,并且控制臺會生成該錯誤“ Uncaught TypeError: Cannot read property 'getAttribute'為空”當刪除等號以使結束條件如下 (i<myArray.length) 時,不再顯示錯誤,但創建的 (myArray) 返回空數組,導航欄上依次不顯示任何項目在網頁上。
1 回答

手掌心
TA貢獻1942條經驗 獲得超3個贊
在數組上添加或刪除元素時,不應迭代數組。一般來說,這是一件有風險的事情,因為它取決于編程語言,而且也很難理解。在這種情況下,最好使用while或do-while循環。
如果你想留在 for 循環中,你可以簡單地添加一個中斷條件。
for ( let i = 0; i < myArray.length; i++){
let triggerSection= document.getElementById( 'section' + ( 1 + i ));
if ( triggerSection === null ) break;
...
}
相反,更好的循環終止條件可能是triggerSection === null,因為如果未找到元素則getElementById返回。null(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
因此這應該有效:
let i = 0;
while ( (let triggerSection = document.getElementById( 'section' + ( 1 + i ))) !== null) {
i++;
}
添加回答
舉報
0/150
提交
取消