使用循环来简化DOM操作Vanilla JS

时间:2016-04-07 18:24:43

标签: javascript loops dry dom-manipulation

我有以下JS代码,我试图将这些元素附加到DOM。我已经这样做了,但是我想弄清楚如何使用循环来追加这些遵循DRY原则。我只能使用香草JS。

var divOne = document.getElementById('buttonHolder');

var btnGroupOne = document.createElement('div')
btnGroupOne.className = 'btn-group';
divOne.appendChild(btnGroupOne);

var btnOne = document.createElement('button');
var textOne = document.createTextNode('1');
btnOne.appendChild(textOne);
btnOne.className = 'btn btn-default';
btnGroupOne.appendChild(btnOne);

var btnTwo = document.createElement('button');
var textTwo = document.createTextNode('2');
btnTwo.appendChild(textTwo);
btnTwo.className = 'btn btn-default';
btnGroupOne.appendChild(btnTwo);

var btnThree = document.createElement('button');
var textThree = document.createTextNode('3');
btnThree.appendChild(textThree);
btnThree.className = 'btn btn-default';
btnGroupOne.appendChild(btnThree);

var btnFour = document.createElement('button');
var textFour = document.createTextNode('4');
btnFour.appendChild(textFour);
btnFour.className = 'btn btn-default';
btnGroupOne.appendChild(btnFour);
<div id="buttonHolder"></div>

1 个答案:

答案 0 :(得分:1)

尽量抽象尽可能多的代码,Andy是正确的函数最适合这类任务:

function buttonMaker(textnode) {
  var btnOne = document.createElement('button');
  var textOne = document.createTextNode(textnode);
  btnOne.appendChild(textOne);
  btnOne.className = 'btn btn-default';
  return btnOne;
}

var numberOfButtons = 4;

var btnHolder = document.createElement('div');

// in a loop you can then do this:
for (var i = 1; i <= numberOfButtons; i++) {
  btnHolder.appendChild(buttonMaker(i));
}

document.getElementById('btnBox').appendChild(btnHolder);
<div id="btnBox"></div>