如何批量添加这些元素?

时间:2015-04-27 14:49:46

标签: javascript

我需要添加这些元素:

<div class="checkbox">
  <label>
    <input type="checkbox" name="optionsRadios" id="optionsRadios1" value="option1">
    <input class="inputone" id="optionsRadios1text" type="text">
  </label>
</div>

到此:

<div id="childs"></div>

有没有办法在不使用多个appendChild函数的情况下执行此操作?

2 个答案:

答案 0 :(得分:3)

如果你还没有在DOM中使用这个标记,那就足够了:

var html = "<div class='checkbox'>"+
"  <label>"+
"    <input type='checkbox' name='optionsRadios' id='optionsRadios1' value='option1'>"+
"    <input class='inputone' id='optionsRadios1text' type='text'>"+
"  </label>"+
"</div>"

var  childs = document.getElementById('childs')

childs.innerHTML = childs.innerHTML + html

如果您需要不断向儿童添加复选框(最好将其称为儿童),您不希望这样做并希望appendChild(checkbox) 您可以在页面的某处添加隐藏标记并使用它。见标记:

<div id='cb' class="checkbox" style='display:none'>
  <label>
    <input type="checkbox" name="optionsRadios" id="optionsRadios1" value="option1">
    <input class="inputone" id="optionsRadios1text" type="text">
  </label>
</div>
<div id="children">content</div>
<button id='btn'>add</button>

和代码:

var btn = document.getElementById('btn')
, children = document.getElementById('children')
, cb = document.getElementById('cb')

btn.addEventListener('click', add)

function add() {
    var n = cb.cloneNode(true)
    n.style.display = '';   
    children.appendChild(n)
}

请参阅jsfiddle

请注意,您在“模板”中使用id属性,因此在多次插入后,您将拥有多个具有相同ID的元素。 您可能需要更新它和/或仅使用name属性。

否则,您可以查询该子节点的DOM,并使用一个appendChild调用将其插入。

答案 1 :(得分:0)

无需调用多个appendChild()函数。

document.getElementById('childs').appendChild(document.querySelector('.checkbox‌​'));