【问题标题】:Create multiple buttons using array.protoype.forEach (javascript)使用 array.prototype.forEach (javascript) 创建多个按钮
【发布时间】:2022-01-14 09:00:45
【问题描述】:

我正在编写一些代码,这些代码将根据给定函数的数组创建多个按钮。我所做的是使用 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

);

【问题讨论】:

    标签: javascript arrays function button foreach


    【解决方案1】:

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

    let array = ["bill", "harry", "john", "timothy"];
    
    array.forEach(element=> { 
      let btn = document.createElement('button');
      btn.innerHTML = element;
      document.body.appendChild(btn);
    });

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-18
        • 1970-01-01
        • 2020-09-15
        • 2021-04-18
        相关资源
        最近更新 更多