JavaScript在循环中创建按钮

时间:2015-06-19 14:39:17

标签: javascript html

我想在每个按钮之后打破并居中,有什么建议吗? setAttribute不起作用,也不添加中断



for (var j = 0; j <= 6; j++) {
  var btn = document.createElement("BUTTON");
  var t = document.createTextNode(sm[j] + " " + sy[j]);
  btn.appendChild(t);
  document.body.appendChild(btn);
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

jsfiddle

<强> HTML

<div id='theParent' class='center_the_stuff'>

</div>

<强> JS

function addInput(type, value, name, id, onclick, parentId) {
    //Create an input type dynamically.   
    var element = document.createElement("input");
    //Assign different attributes to the element. 
    element.type = type;
    element.value = value; // Really? You want the default value to be the type string?
    element.name = name; // And the name too?
    element.id = id;
    element.onclick = onclick;

    var parent = document.getElementById(parentId);
    //Append the element in page (in span).  
    parent.appendChild(element);
}

function addBreak(parentId) {
    var br = document.createElement("br");
    var parent = document.getElementById(parentId);
    parent.appendChild(br);
}

window.onload = function () {
    for (var j = 0; j <= 6; j++) {
        var temp = 'mybutton' + j;
        addInput('button', temp, temp, temp, undefined, 'theParent');
        addBreak('theParent');
    }
}

<强> CSS

.center_the_stuff {
    text-align: center;
}