当我点击复制时,它会复制该行,但是当我再次点击它时,我得到另一个2,然后是4等,我怎么能阻止这种情况发生,只需在每次点击时克隆一个div ...
Jquery的:
<script>
$(".clonable-button").bind('click', function(e){
e.preventDefault();
var section = $(this).data('clone');
var parent = $('[data-id="' + section + '"]');
var sequence = 0;
if(!$(this).data('last')) {
sequence = $(parent).find('.cloneable').last().data('id');
} else {
sequence = $(this).data('last');
}
$(this).data('last', ++sequence);
$(parent).append(parent.html());
});
$('.clone-wrapper').on('click', '.clone-remove',function(){
var parent = $(this).parents('.cloneable');
$(parent).remove();
});
</script>
HTML:
<div class="clone-wrapper" data-id="skill">
<div class="row cloneable" data-id="0">
<div class="col-md-9">
<div class="form-group">
<label for="skill_name_0">Skills and Qualifications Titles </label>
<input id="skill_name_0" placeholder="ex : PHP, WordPress" name="skill[0][name]" type="text" class="form-control" value="">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="skill_percentage_0">Job Position </label>
<input id="skill_percentage_0" placeholder="ex : 90" name="skill[0][percentage]" type="text" class="form-control" value="">
</div>
</div>
<div class="col-md-12 text-right clone-remove" data-last="">
<div class="btn btn-danger btn-sm" data-clone="skill">
<i class="fa fa-times"></i> Remove Skill </div>
</div>
</div>
</div>
<div class="white-space-20"></div>
<div class="row text-right">
<div class="col-md-12">
<div class="btn btn-default btn-sm clonable-button" id="skill">
<i class="fa fa-plus"></i> Add Skill </div>
</div>
</div>
我只想在每次点击时复制以下代码一次
<div class="row cloneable" data-id="0">
<div class="col-md-9">
<div class="form-group">
<label for="skill_name_0">Skills and Qualifications Titles </label>
<input id="skill_name_0" placeholder="ex : PHP, WordPress" name="skill[0][name]" type="text" class="form-control" value="">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="skill_percentage_0">Job Position </label>
<input id="skill_percentage_0" placeholder="ex : 90" name="skill[0][percentage]" type="text" class="form-control" value="">
</div>
</div>
<div class="col-md-12 text-right clone-remove" data-last="">
<div class="btn btn-danger btn-sm" data-clone="skill">
<i class="fa fa-times"></i> Remove Skill </div>
</div>
</div>
答案 0 :(得分:1)
问题出在这一行:
var parent = $('[data-id="' + section + '"]');
每次添加具有相同数据ID的新块时,与此选择器匹配的元素数量都会增加。因此,为了避免这种情况,您可以使选择器更具体。像:
var parent = $('[data-id="' + section + '"]:last');
还有一个克隆元素的jQuery方法。所以改变你的行:
$(parent).append(parent.html());
为:
parent.append(parent.clone());
这将解决问题。
答案 1 :(得分:0)
您以某种方式多次绑定click事件,您应该使用委托事件处理程序或使用如下所示的off
方法。
$(".clonable-button").off('click').on('click', function(e){