如何在JS中动态创建一组元素

时间:2014-07-03 16:56:48

标签: javascript jquery html dynamic

我如何创建一组元素,即不仅仅是div而是div的集合可能是这样的

<div class="row">
  <div class="col-xs-12">
    <div class="box" style='padding-bottom:0px;'>

      <div class="box-content" style='z-index:-1;'>
        <div class="box">

          <div class="avatar">
            <img src="src" alt="Profile" style="width: 80px;height:80px;"/>
          </div>
          <div class="page-feed-content">
            <a href='href'>
            <small class="label label-primary"></small>

通常我一个接一个地创建它并使用appendchild函数,我将孩子附加到父母身上,但这是一个繁忙的任务。如何使用native或jQuery在js上轻松动态创建这组HTML元素?

1 个答案:

答案 0 :(得分:1)

创建一个通用处理程序并在循环中运行它:

function CreateElement(elemParent, sTagName, aAttributes)
{
   // Use your create element code here where elemParent is the parent 
   // sTagName is your Tag name and 
   // aAttributes is a collection of attributes to set on your new element
}

for (var i = 0; i < nLimit; i += 1)
   CreateElement(elemParent, "sTagName", [{ Key : Value }, { Key : Value }]);

以下是另一个可以帮助您的链接:What is the most efficient way of creating an HTML element and appending attributes to it and then wrapping it inside of another element?