【问题标题】:clone a div and insertAfter last child of siblings within relative parents克隆一个 div 并在相对父母中的兄弟姐妹的最后一个孩子之后插入
【发布时间】:2015-09-08 16:55:38
【问题描述】:

我的标记是这样的:--

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

我希望当我单击按钮时,它只克隆一个最近的兄弟姐妹,并在相对父 div.wrap 中的最后一个兄弟姐妹之后插入克隆 div。我知道如何使用 jQuery 进行克隆,但我无法在相对父级中的最后一个兄弟姐妹之后插入克隆的 div。

【问题讨论】:

  • 那么如果我点击上面示例中的第一个按钮,结果应该是什么?
  • 如果我点击按钮
    将被克隆并添加到它的最后一个
    父包装 div 之后。同样,如果我单击
    它将克隆并在其父包装 div 中的最后一个
    之后添加。

标签: javascript jquery


【解决方案1】:

您可以使用.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>

【讨论】:

    【解决方案2】:

    如果我理解正确,您应该可以使用.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>

    【讨论】:

      【解决方案3】:

      如果我正确理解了问题

      $('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>

      【讨论】:

        猜你喜欢
        • 2015-03-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-04
        • 2023-03-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多