JavaScript:for循环附加元素在几个地方 [英] JavaScript: for loop append element in several places

查看:24
本文介绍了JavaScript:for循环附加元素在几个地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个for循环,需要将列表项附加到共享相同类名的两个菜单中.问题在于,如果我引用了它的索引,它只会追加到一个或另一个,或者如果我使用I的索引,它将只追加到最后一个.

I have a for loop that needs to append a list item to two menus sharing the same class name. The problem is it will only append to one or the other if I reference the index of it or if I use index of I it will only append to the last item.

HTML

<ul class="menu">
<li>List One</li>
</ul>

<ul class="menu">
<li>List Two</li>
</ul>

JS

var menu    = document.querySelectorAll('.menu');
var listItem    = document.createElement('li');

for(i=0; i < menu.length; ++i){
    menu[i].appendChild(listItem);
}

这是JS的另一个怪癖还是我只是想念一些东西?

Is this another weird quirk of JS or am I just missing something?

推荐答案

应该是...

var menu = document.querySelectorAll('.menu');
var listItem = document.createElement('li');

for (var i=0; i < menu.length; ++i) {
    menu[i].appendChild(listItem.cloneNode());
    // or menu[i].appendChild(document.createElement('li'));
    // the point is, you'll have to create a new element and append it
}

按现状,您只需将同一元素从一个父 .menu 项移动到另一项.引用文档:

As it stands, you just move the same element from one parent .menu item to another. Quoting the docs:

如果给定子级是对节点中现有节点的引用文档,appendChild()将其从当前位置移动到新位置位置(无需从其父节点中删除该节点节点,然后再将其附加到其他节点).

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (there is no requirement to remove the node from its parent node before appending it to some other node).

这篇关于JavaScript:for循环附加元素在几个地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆