使用 array.protoype.forEach (javascript) 创建多个按钮

Create multiple buttons using array.protoype.forEach (javascript)

我正在编写一些代码,这些代码将根据提供给函数的数组创建多个按钮。我所做的是,我使用 array.prototype.forEach 通过在控制台上打印数组的内容来测试函数。当它起作用时,我尝试制作一些按钮,但按钮没有显示在页面上。我尝试添加 document.body.appendChild(element); 但所做的只是给我错误。有没有一种方法可以使用 array.protoype.forEach?

基于项目数组创建多个按钮

这是我的代码:

var array = ["bill", "harry", "john", "timothy"];

array.forEach(element => 
  document.createElement(element)
//I tried adding document.body.appendChild(element); here but kept giving me errors

);

使用forEach时,在写多行表达式时要注意{}的使用。在下面的示例中,加载页面时,它使用数组数组中的数据创建 <button> 元素。在此解决方案中,在每个 forEach 循环中创建一个 <button> 元素,并将其添加到子元素 idcontainer.[=21= 的 <div> 元素中]

var container = document.getElementById('container');
var array = ["bill", "harry", "john", "timothy"];
let identifier = 0;

array.forEach(element => {
    /* The new <button> element is created. */
    var button = document.createElement("button");
    
    /* The <button> element is assigned an "id". */
    button.id = element;
    
    /* A text node is added to the new <button> element. */
    var text = document.createTextNode(element);
    
    /* The text node is added to the <button>. */
    button.appendChild(text);
    
    /* The created <button> element is bound to the container as a child node. */
    container.appendChild(button);
});
button{
  display: block;
  width: 75px;
  margin-bottom: 5px;
}

/* The style created to verify that the id has been added to the created <button> element. */
#bill{
 background-color: red;
}
<div id="container">
  <!-- <button> elements are added to this field. -->
</div>

您传递给 document.createElement 的第一个参数是一个字符串,它指定要创建的元素的类型。您的代码中的另一个问题是,虽然您的函数主体是多行的,但您没有使用 {},您可以这样实现您的目标:

let array = ["bill", "harry", "john", "timothy"];

array.forEach(element=> { 
  let btn = document.createElement('button');
  btn.innerHTML = element;
  document.body.appendChild(btn);
});