【问题标题】:Making HTML buttons from an array of names, and inserting them into the DOM从名称数组中制作 HTML 按钮,并将它们插入 DOM
【发布时间】:2021-11-09 17:16:13
【问题描述】:

我不知道如何使用数组将这些变成按钮:

var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]

任何帮助将不胜感激。这是我正在尝试使用的代码

   <body>
   <div id="demo"></div>
   <script>
        var widgetButtons = ["Zoom In", "Zoom Out", "Pan", 
        "Search"];
   </script>
   </body>
   </html>

【问题讨论】:

    标签: javascript html button


    【解决方案1】:

    这是另一种方法,使用forEach()

    ID 不能包含空格,因此我们在设置 ID 之前从项目名称/文本中删除空格。

    const widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"]
    const demo = document.getElementById('demo');
    
    widgetButtons.forEach( (item, idx) => {
      const btn = document.createElement('button');
      btn.id = item.replace(' ', '');
      btn.innerText = item;
      demo.appendChild(btn);
    });
    <html>
      <body>
        <div id="demo"></div>
      </body>
    </html>

    【讨论】:

      【解决方案2】:

      在您的 HTML 中:&lt;div id="new"&gt;

      在你的 JS/脚本中:

      var widgetButtons = ["Zoom In", "Zoom Out", "Pan",
            "Search"];
          var element = document.getElementById("new");
      
          for (const widgetButtonsKey of widgetButtons) {
            var x = document.createElement("BUTTON");
            x.innerText = widgetButtonsKey
            console.log(x);
            element.appendChild(x);
          }
      

      【讨论】:

        【解决方案3】:

        这是另一种方法。

        var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"];
        document.getElementById('demo').innerHTML = widgetButtons.map(text=>{
          return `<button>${text}</button>`;
        }).join(' ');
        &lt;div id=demo&gt;&lt;/div&gt;

        【讨论】:

          【解决方案4】:
              const demo = document.getElementById("demo");
          
              var widgetButtons = ["Zoom In", "Zoom Out", "Pan", 
              "Search"];
          
              //Loop through the array
              for (let index = 0; index < widgetButtons.length; index++) 
              {
                  //Create button element using create element
                  const button = document.createElement("button");
                  //This adds button value (title of the button)
                  button.innerHTML = widgetButtons[index];
                  //Add style to increase margin
                  button.style.margin = "10px";
                  //Append the buttons created to the body
                  demo.appendChild(button);
               }
          

          【讨论】:

          • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
          猜你喜欢
          • 1970-01-01
          • 2015-06-23
          • 1970-01-01
          • 1970-01-01
          • 2017-10-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多