[英]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>
元素,並將其添加到子元素id
為container
的<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.