如何在使用jQuery追加之前克隆,修改(增加一些元素)?

时间:2016-07-21 09:55:10

标签: javascript jquery

我有一个元素,里面包含多个元素,我需要的是克隆元素,但是在每个“new”元素上,我需要增加一个元素(对象编号 - 请看我的脚本 - )

在我添加的脚本中我需要(每次点击按钮)都有:Hello#1(默认情况下是第一个)但是第一次点击make:Hello#2(并保持在顶部你好) #1)第二次点击=你好#1你好#2你好#3 ......我们需要保留最老的hellos并显示第一个。

var count = 1;
$(".button").click(function(){    
 	 count += 1;
    num = parseInt($(".object span").text());
    $(".object span").text(count);
    
   var cont = $(".container"),
   div = cont.find(".object").eq(0).clone();    
   cont.append(div);
});
.object{
  width:100px;
  height:20px;
  background-color: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
create object
</button>

<div class="container">
  <div class="object">
  <p>
  

     hello#<span>1</span>
    </p>
  </div>


</div>

2 个答案:

答案 0 :(得分:3)

你只需改变一点:

&#13;
&#13;
var count = 1;
$(".button").click(function() {
  count += 1;
  num = parseInt($(".object span").text());


  var cont = $(".container"),
    div = cont.find(".object").eq(0).clone();
  div.find('span').text(count); // <------here you have to put the count
  cont.append(div);
});
&#13;
.object {
  width: 100px;
  height: 20px;
  background-color: gold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
  create object
</button>

<div class="container">
  <div class="object">
    <p>
      hello#<span>1</span>
    </p>
  </div>


</div>
&#13;
&#13;
&#13;

如果你想简化这个,可以使用:

&#13;
&#13;
$(".button").click(function() {
  var idx = ++$('.object').length; // check for length and increment it with ++
  var cont = $(".container"),
      div = cont.find(".object").eq(0).clone();
  div.find('span').text(idx); // <------here you have to put the count
  cont.append(div);
});
&#13;
.object {
  width: 100px;
  height: 20px;
  background-color: gold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
  create object
</button>

<div class="container">
  <div class="object">
    <p>
      hello#<span>1</span>
    </p>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用以下功能,这是更模块化的,如果你删除其中一个元素,你可以用它来更新计数

&#13;
&#13;
function updateCount() {
  $(".object").each(function(i,v) {
    $(this).find("span").text(i+1);
  });
}
$(".button").click(function() {
  num = parseInt($(".object span").text());
  var cont = $(".container"),
  div = cont.find(".object").eq(0).clone();
  cont.append(div);

  updateCount();
});
&#13;
.object {
  width: 100px;
  height: 20px;
  background-color: gold;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<button type="button" class="button">
  create object
</button>

<div class="container">
  <div class="object">
    <p>
      hello#<span>1</span>
    </p>
  </div>


</div>
&#13;
&#13;
&#13;