我有一个元素,里面包含多个元素,我需要的是克隆元素,但是在每个“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>
答案 0 :(得分:3)
你只需改变一点:
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;
如果你想简化这个,可以使用:
$(".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;
答案 1 :(得分:1)
使用以下功能,这是更模块化的,如果你删除其中一个元素,你可以用它来更新计数
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;