我的标记是这样的:--
<div class="wrap">
<div class="a"></div>
<div class="a"></div>
<button type="button">press</button>
</div>
.
.
.
<div class="wrap">
<div class="z"></div>
<button type="button">press</button>
</div>
我希望当我单击按钮时,它仅克隆一个最接近的 sibling ,并将克隆 div 插入到相对父 div.wrap 中的最后一个 sibling 之后。我知道如何使用 jQuery 克隆,但无法在相对父级中的最后一个 sibling 之后插入克隆的 div 。
最佳答案
您可以使用 .before()
在按钮之前插入,并使用 .prev()
克隆按钮上方的 div:
$('.wrap > button').on('click', function() {
$(this).before( $(this).prev().clone() );
});
$('.wrap > button').on('click', function() {
$(this).before( $(this).prev().clone() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrap">
<div class="a">A1</div>
<div class="a">A2</div>
<button type="button">press</button>
</div>
<div class="wrap">
<div class="z">Z1</div>
<button type="button">press</button>
</div>
关于javascript - 克隆一个 div 并插入到亲戚 parent 中 sibling 的最后一个 child 之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32463264/