我不知道如何使用陣列將這些變成按鈕:
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>
uj5u.com熱心網友回復:
這是另一種方法,使用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>
uj5u.com熱心網友回復:
在您的 HTML 中: <div id="new">
在您的 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);
}
uj5u.com熱心網友回復:
這是另一種方法。
var widgetButtons = ["Zoom In", "Zoom Out", "Pan", "Search"];
document.getElementById('demo').innerHTML = widgetButtons.map(text=>{
return `<button>${text}</button>`;
}).join(' ');
<div id=demo></div>
uj5u.com熱心網友回復:
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);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/366430.html
標籤:javascript html 按钮
上一篇:我的按鈕不作業,我怎樣才能讓它在androidstudio上作業?
下一篇:漸變色ggplot2R中的一條線
