使用jquery创建元素并为它们提供不同的类

时间:2017-11-28 16:18:42

标签: javascript jquery

克隆.clone拥有的每个孩子

<section class="clone">
   <div class="input-group">
      <input type="text" class="form-control" placeholder="insert step 2 title*">
   </div>
</section>

使用点击功能进行克隆

$('.btnAnotherStep').on('click',function(){
    var copy =  $('.clone>*').clone();
    $('.container').append(copy);

一切都好,但我的问题是;是否可以为克隆的输入提供不同的类名。等;

<input type="text" class="form-control input2" placeholder="insert 
step 2 title*">
<input type="text" class="form-control input3" placeholder="insert step 2 title*">
<input type="text" class="form-control input4" placeholder="insert step 2 title*">

我的第一个意见是使用jquery从头开始创建每个元素,并将类名称递增i加1

var totalInputs = [];
var i = 0;
while(i < 10){
  var input = $("input", {"class": "input[i]"); //but its not possible to refer like that 
  $('body').append(input);
  i++;
}

任何方法都可以这样做,因为""里面标明它并不像数字那样?

2 个答案:

答案 0 :(得分:0)

.clone()之后,您可以执行.each()循环遍历所有元素,并对其中的类进行任何更改。如果它们是嵌套元素,您还需要在每个子元素上运行它。如果是这种情况,您将需要将类更改功能分开,以便它可以递归运行。

这样的事情:

const changeClass = element => {
  // do something here to change the class name how you want for $(element)
  $(element).children().each(changeClass);
};

$('.btnAnotherStep').on('click',function(){
  var copy =  $('.clone>*').clone().each(changeClass);
  $('.container').append(copy);
});

你对班级名称的所作所为取决于你,但它可能是某种字符串转换。

答案 1 :(得分:0)

您可以循环遍历克隆元素,在each循环中获取索引并将该索引放在模板文本中或传统上通过字符串连接。无需在初始点击事件之外创建额外的循环:

$(function() {
  $('.btnAnotherStep').on('click',function(){
    var copy =  $('.clone > *').clone();

    copy.each(function(index, elem) {
      const $this = $(this);

      if ($this.is('input')) {
        $this.addClass(`input${i}`);
      }
    });

    $('.container').append(copy);
  });
});