繁体   English   中英

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

[英]Create multiple buttons using array.protoype.forEach (javascript)

我正在编写一些代码,这些代码将根据给定给 function 的数组创建多个按钮。 我所做的是,我使用 array.prototype.forEach 通过在控制台上打印数组的内容来测试 function。 当它起作用时,我尝试制作一些按钮,但这些按钮没有显示在页面上。 我试过添加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
);

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

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

使用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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM