为什么在forEach循环中不会追加列表项? [英] Why would list items not be appending while in a forEach loop?

查看:37
本文介绍了为什么在forEach循环中不会追加列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的forEach循环,在该循环中,我试图将列表项追加到无序列表中.但是,当我运行脚本时,我只会看到一个列表项被添加.谁能解释为什么会这样?

I have a simple forEach loop in which I'm trying to append list items to an unordered list. However, when I run the script, I'm only seeing one list item being added. Can anyone explain why this is happening?

JS

let bookElement = document.getElementsByClassName("book");
let navElement = document.getElementsByTagName("nav")[0];
let unorderedList = document.createElement("UL");
let listItems = document.createElement("LI");
let book1 = new Book();
let book2 = new Book();
let booksArray = [book1, book2];

createNavigation(booksArray, navElement, unorderedList, listItems);

function createNavigation(booksArray, navElement, unorderedList, listItems){
    console.log(booksArray)
    booksArray.forEach(function(book){
        unorderedList.appendChild(listItems);
    })
    navElement.appendChild(unorderedList);
}

HTML

<body>
    <nav></nav>
    <div class="book"></div>
</body>

函数中的日志返回该数组中有两个对象.

The log in the function is returning that there are two objects in the array.

推荐答案

您只能创建一个列表项.

You only ever create one list item.

然后将其附加到多个位置.

You then append it in multiple places.

由于一个元素不能同时存在于多个位置,因此每次添加(在第一个元素之后)都可以移动.

Since an element can't exist in multiple places at the same time, each time you append it (after the first) you move it.

在循环中使用 let listItems = document.createElement("LI"); .

这篇关于为什么在forEach循环中不会追加列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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