简体   繁体   English

克隆div并在相对父母的兄弟姐妹的最后一个孩子之后插入

[英]clone a div and insertAfter last child of siblings within relative parents

My markup like this:-- 我的标记如下:

<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>

I want when I click the button it clone only one closest siblings and insert the clone div after the last siblings within relative parent div.wrap. 我想要单击按钮时仅克隆一个最接近的兄弟姐妹,并将克隆div插入相对父div.wrap中最后一个兄弟姐妹之后。 I know how to clone with jQuery but I couldn't insert the cloned div after last siblings within relative parent . 我知道如何用jQuery克隆,但是我无法在相对父级的最后一个兄弟姐妹之后插入克隆的div。

You can use .before() to insert before the button and .prev() to clone the div above the button: 您可以使用.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> 

If I understand correctly, you should be able to use .prev() to find the previous div, then append a clone using .after() . 如果我理解正确的话,你应该能够使用.prev()找到以前的DIV,然后附加一个使用克隆.after()

 $(".wrap button").click(function() { var prev = $(this).prev("div"); prev.after(prev.clone()); }); 
 div { margin: 5px; } .a { height: 100px; width: 100px; background-color: green; } .z { height: 100px; width: 100px; background-color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="wrap"> <div class="a"></div> <button type="button">press</button> </div> <div class="wrap"> <div class="z"></div> <button type="button">press</button> </div> 

if i correctly understood problem 如果我正确理解问题

 $('button').on('click', function(){ var siblings = $(this).siblings(); siblings.last().clone().insertAfter(siblings.last() ) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM