我想创建这些按钮:
<!DOCTYPE html>
<html>
<body>
<button type="button">Linear algebra </button>
<button type="button">Calculus I </button>
<button type="button">Basic Mechanics </button>
<button type="button">Mechanics1 </button>
<button type="button">Mechanics2 </button>
<button type="button">Mechanics3 </button>
<button type="button">Mechanics4 </button>
<button type="button">Mechanics5 </button>
</body>
</html>
我想知道是否有一个选项,可以在列表更长的时候使用函数。 我的想法是创建以下列表:
var subjects=["Linear algebra","Calculus I","Basic Mechanics","Mechanics1","Mechanics2","Mechanics3","Mechanics4","Mechanics4"]
使用for循环迭代它,然后使用列表中每个元素的结果创建按钮。这可能吗?
答案 0 :(得分:0)
您可以使用Array forEach遍历数组,使用createElement创建按钮,然后appendChild将它们附加到需要的DOM中。
var subjects=["Linear algebra","Calculus I","Basic Mechanics","Mechanics1","Mechanics2","Mechanics3","Mechanics4","Mechanics4"]
subjects.forEach(function(item){
var button = document.createElement('button');
button.type = 'button';
button.innerHTML = item;
document.body.appendChild(button);
})
&#13;
答案 1 :(得分:0)
const subjects=["Linear algebra","Calculus I","Basic Mechanics","Mechanics1","Mechanics2","Mechanics3","Mechanics4","Mechanics4"]
for (const item of subjects) {
const button = `<button type="button">${item}</button>`
document.body.insertAdjacentHTML("beforeend", button);
}
&#13;