如何动态地将类添加到div

时间:2014-09-07 10:19:18

标签: jquery css

我需要动态添加一个类,因为我使用addClass方法然后类正在添加,但它不符合我的要求。这是我的代码

 <div id="form-copy">
   <div class="abc">
       Here some code is there....
   <div>
 <div>

我正在尝试这样......

  var p = 0;
  for(var i =0; i<n;i++){
    $(".abc:first").clone(true).appendTo("#form-copy")
    $(".abc").addClass( "dynamicClass"+ ++p);
  }
now am getting output is...
 if here n=3
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>
     <div class="abc dynamicClass1 dynamicClass2 dynamicClass3">...</div>

But i need output like this
  if here n=3
     <div class="abc dynamicClass1">...</div>
     <div class="abc dynamicClass2">...</div>
     <div class="abc dynamicClass3">...</div>

Plese help me to get like this output.Thank you

2 个答案:

答案 0 :(得分:1)

for(var i =0; i<n;i++){
    $(".abc:first").clone().appendTo("#form-copy").addClass("dynamicClass" + (i + 1));
  }

答案 1 :(得分:0)

编辑:试试这个:

<div id="form-copy">
  <div class="abc" id="abc">
    Here some code is there....
 </div>
</div>


var p = 0;
for( var i = 0; i < n;i++ ){
    $(".abc:first").clone(true).appendTo("#form-copy")
    $("#abc").removeClass().addClass( "abc dynamicClass"+ ++p);
}