我正在撰寫一些代碼,這些代碼將根據給定函式的陣列創建多個按鈕。我所做的是使用 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
);
uj5u.com熱心網友回復:
您傳遞給document.createElement的第一個引數是一個字串,它指定要創建的元素的型別。您的代碼中的另一個問題是,雖然您的函式體是多行的,但您沒有使用{},您可以像這樣實作您的目標:
let array = ["bill", "harry", "john", "timothy"];
array.forEach(element=> {
let btn = document.createElement('button');
btn.innerHTML = element;
document.body.appendChild(btn);
});
uj5u.com熱心網友回復:
使用時forEach,要注意{}寫多行運算式時的使用。在下面的示例中,當頁面加載時,它<button>使用陣列陣列中的資料創建元素。在此解決方案中,<button>在每個forEach回圈中創建一個元素,并將其添加到<div>其子元素id為的元素中container。
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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/410841.html
標籤:
