如何使用jQuery单击复制div? [英] How to duplicate div on click with jQuery?

查看:397
本文介绍了如何使用jQuery单击复制div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望单击button时在其后复制一个div.我找到了 JS 解决方案,但我需要一个 jQuery ,我真的很不好. 有人可以帮我吗?

I want a div to be duplicated after itself when a button is clicked. I found JS solutions but I need a jQuery one and I'm really bad at it. Can anyone help me please?

这就是我所拥有的:

<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

这就是我需要的(单击后):

That's what I need (after click):

<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>

  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

推荐答案

使用.clone()复制div,然后添加.after().由于您使用的是类,因此您可能只希望复制一个div,在这种情况下,您应该使用.closest().另外,您还需要传递一个布尔参数来进行克隆,以便将所有数据和事件处理程序附加到克隆的元素上.

Make use of .clone() to copy the div and .after() to append. Since you are using class you may want to copy only one div, in that case you should use .closest(). Also you need to pass a boolean parameter to clone so that all data and event handlers will be attached to cloned element.

$(function(){
  $(".btn-copy").on('click', function(){
    var ele = $(this).closest('.example-2').clone(true);
    $(this).closest('.example-2').after(ele);
  })
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="example-1">
  <div class="example-2"> 
    <p>Example one</p>
    <p>Example two</p>

    <button class="btn-copy">Copy</button>
  </div>
</div>

这篇关于如何使用jQuery单击复制div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆