[英]Vanilla JS - Looping through a list and inserting an element causes infinite loop error
I have a nav menu and want to add a decorative element between each item.我有一个导航菜单,想在每个项目之间添加一个装饰元素。 Outside of the loop my code seems to work when I target a specific list item with [0], but when used inside the loop using [i] the page never finishes loading.
在循环之外,当我使用 [0] 定位特定列表项时,我的代码似乎可以工作,但是当在循环内部使用 [i] 时,页面永远不会完成加载。
When i move to JSbin to test, I am getting infinite loop errors.当我转移到 JSbin 进行测试时,我遇到了无限循环错误。
HTML: HTML:
<ul id="menu-mobile-navigation">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Etc</li>
</ul>
JS: JS:
var mobileNav = document.getElementById('menu-mobile-navigation');
var mobileNavChildren = mobileNav.children;
// var decoration = document.createElement('div');
// decoration.classList.add( 'decoration' );
// mobileNav.insertBefore( decoration, mobileNavChildren[0].nextSibling ); // works outside loop
for (var i = 0; i < mobileNavChildren.length; i++) {
var decoration = document.createElement('div');
decoration.classList.add( 'decoration' );
mobileNav.insertBefore( decoration, mobileNavChildren[i].nextSibling ); // page never loads, infinite loop error in JSbin
}
The .children
of an element returns a live HTMLCollectio, which will mutate even as you iterate over it if elements get added to it in the middle of looping:元素的
.children
返回一个活动的 HTMLCollectio,如果在循环中间添加了元素,即使在迭代它时它也会发生变化:
var mobileNav = document.getElementById('menu-mobile-navigation'); var mobileNavChildren = mobileNav.children; console.log(mobileNavChildren.length); mobileNav.appendChild(document.createElement('div')); console.log(mobileNavChildren.length);
<ul id="menu-mobile-navigation"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Etc</li> </ul>
You want a static collection instead - consider using querySelectorAll
, or spreading into an array:你想要一个 static 集合代替 - 考虑使用
querySelectorAll
,或者传播到一个数组中:
const mobileNav = document.getElementById('menu-mobile-navigation'); const mobileNavChildren = mobileNav.querySelectorAll('li'); for (var i = 0; i < mobileNavChildren.length; i++) { var decoration = document.createElement('div'); decoration.classList.add( 'decoration' ); mobileNav.insertBefore( decoration, mobileNavChildren[i].nextSibling ); }
<ul id="menu-mobile-navigation"> <li>One</li> <li>Two</li> <li>Three</li> <li>Four</li> <li>Etc</li> </ul>
Though, also note that a <div>
should not be a child of a <ul>
- only list elements should be children of a <ul>
.不过,还要注意
<div>
不应该是<ul>
的子元素 - 只有列表元素应该是<ul>
的子元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.