我的代码-Fiddle
// clone item
$(document).on('click', '.add-item', function() {
var lastItem = $(this).parents('.container').find('.item-origin').last();
$(this).parents('.item-help').hide();
var newItem = lastItem.clone().insertAfter(lastItem);
});
// close item
$(document).on('click', '.close', function(e) {
e.preventDefault();
$(this).closest('.item-origin').remove();
$('.item-help').each(function() {
if ($(this).is(':hidden')) {
$(this).show();
}
});
});
.row {
display: flex;
padding: 15px;
border: 1px solid #ccc;
}
.item {
border: 1px solid #ccc;
padding: 15px;
width: calc(100% / 3);
text-align: center;
}
label {
display: inline-block;
vertical-align: top;
margin-bottom: 10px;
}
label+label {
margin-left: 15px;
}
.item {
position: relative;
}
.close {
position: absolute;
top: -10px;
right: 0;
color: #fff;
background: #f00;
font-size: 10px;
padding: 5px;
}
.item:first-of-type .close {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="item item-origin">
<a href="javascript:void(0)" class="close">Close</a> Block origin
</div>
<div class="item item-help">
<a href="javascript:void(0)" class="add-item">Add Item 2</a>
</div>
<div class="item item-help">
<a href="javascript:void(0)" class="add-item">Add Item 3</a>
</div>
</div>
</div>
当我单击Add Item 2
和Additem 3
时,然后使块item-help
不可见
就像在单击克隆项目的.close
时一样,这样仅显示一个块
最大可以是三个块。
如何正确实施?
据我了解,这段代码中最有可能出现的问题
$('.item-help').each(function() {
if ($(this).is(':hidden')) {
$(this).show();
}
});
任何帮助我都会很高兴
谢谢
答案 0 :(得分:1)
尝试一下...我更改了新项目的插入位置并关闭了按钮单击功能
$(document).on('click', '.add-item', function() {
var lastItem = $(this).parents('.container').find('.item-origin').last();
$(this).parents('.item-help').hide();
var newItem = lastItem.clone().insertBefore($(this).parents('.item'));
});
// close item
$(document).on('click', '.close', function(e) {
e.preventDefault();
$(this).closest('.item-origin').next().show();
$(this).closest('.item-origin').remove();
});
.row {
display: flex;
padding: 15px;
border: 1px solid #ccc;
}
.item {
border: 1px solid #ccc;
padding: 15px;
width: calc(100% / 3);
text-align: center;
}
label {
display: inline-block;
vertical-align: top;
margin-bottom: 10px;
}
label+label {
margin-left: 15px;
}
.item {
position: relative;
}
.close {
position: absolute;
top: -10px;
right: 0;
color: #fff;
background: #f00;
font-size: 10px;
padding: 5px;
}
.item:first-of-type .close {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="item item-origin">
<a href="javascript:void(0)" class="close">Close</a>
Block origin
</div>
<div class="item item-help">
<a href="javascript:void(0)" class="add-item">Add Item 2</a>
</div>
<div class="item item-help">
<a href="javascript:void(0)" class="add-item">Add Item 3</a>
</div>
</div>
</div>