我知道如何只生成一个按钮。我这样做是这样的:
var mylist = ['first', 'second', 'third', 'fourth', 'fifth']
var rand = Math.floor(Math.random() * mylist.length)
var word = mylist[rand]
var btn = document.createElement('input')
btn.id = 'b1'
btn.value = word
btn.type = 'button'
document.body.appendChild(btn)
但是我需要生成一些按钮(例如3个按钮)。
document.body.appendChild(btn)
最佳答案
只需将您的逻辑包装在for循环中即可。
范例:
var mylist = ['first', 'second', 'third', 'fourth', 'fifth']
var rand = null;
var word = null;
var threshold = 3
for(var i = 0 ; i < threshold ; i++){
rand = Math.floor(Math.random() * (mylist.length - 1)) + 1;
word = mylist[rand];
var btn = document.createElement('input');
btn.id = 'b' + i;
btn.value = word;
btn.type = 'button';
document.body.appendChild(btn);
}
带有证明的更新:
http://codepen.io/theConstructor/pen/WoJEGy?editors=1010
希望这可以帮助。
关于javascript - 如何在JavaScript中生成三个按钮?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41008448/